import matplotlib.pyplot as plt import numpy as np from votes import wide as df
# Initialise a figure. subplots() with no args gives one plot. fig, ax = plt.subplots()
# A little data preparation years = df['year'] x = np.arange(len(years))
# Plot each bar plot. Note: manually calculating the 'dodges' of the bars ax.bar(x - 3*width/2, df['conservative'], width, label='Conservative', color='#0343df') ax.bar(x - width/2, df['labour'], width, label='Labour', color='#e50000') ax.bar(x + width/2, df['liberal'], width, label='Liberal', color='#ffff14') ax.bar(x + 3*width/2, df['others'], width, label='Others', color='#929591')
# Customise some display properties ax.set_ylabel('Seats') ax.set_title('UK election results') ax.set_xticks(x) # This ensures we have one tick per year, otherwise we get fewer ax.set_xticklabels(years.astype(str).values, rotation='vertical') ax.legend()
import seaborn as sns from votes import long as df
# Some boilerplate to initialise things sns.set() plt.figure()
# This is where the actual plot gets made ax = sns.barplot(data=df, x="year", y="seats", hue="party", palette=['blue', 'red', 'yellow', 'grey'], saturation=0.6)
from bokeh.io import show, output_file from bokeh.models import ColumnDataSource, FactorRange, HoverTool from bokeh.plotting import figure from bokeh.transform import factor_cmap from votes import long as df
# Specify a file to write the plot to output_file("elections.html")
# Tuples of groups (year, party) x = [(str(r[1]['year']), r[1]['party']) for r in df.iterrows()] y = df['seats']
# Bokeh wraps your data in its own objects to support interactivity source = ColumnDataSource(data=dict(x=x, y=y))
# Set up the colourmap cmap = { 'Conservative': '#0343df', 'Labour': '#e50000', 'Liberal': '#ffff14', 'Others': '#929591', }
# Cast years to strings df['year'] = df['year'].astype(str)
# Here's where we make the plot chart = alt.Chart(df).mark_bar().encode( x=alt.X('party', title=None), y='seats', column=alt.Column('year', sort=list(df['year']), title=None), color=alt.Color('party', scale=alt.Scale(domain=list(cmap.keys()), range=list(cmap.values()))) )
# Save it as an HTML file. chart.save('altair-elections.html')
结果图表:
Pygal
Pygal 专注于视觉外观。它默认生成 SVG 图,所以你可以无限放大它们或打印出来,而不会被像素化。Pygal 绘图还内置了一些很好的交互性功能,如果你想在 Web 应用中嵌入绘图,Pygal 是另一个被低估了的候选者。
# Set up the bar plot, ready for data c = pygal.Bar( title="UK Election Results", style=custom_style, y_title='Seats', width=1200, x_label_rotation=270, )
# Add four data sets to the bar plot c.add('Conservative', df['conservative']) c.add('Labour', df['labour']) c.add('Liberal', df['liberal']) c.add('Others', df['others'])
# Define the X-labels c.x_labels = df['year']
# Write this to an SVG file c.render_to_file('pygal.svg')