https://github.com/datawhalechina/fantastic-matplotlib
第二回:艺术画笔见乾坤
# 数据导入代码 # 导入包 import matplotlib.pyplot as plt import numpy as np import pandas as pd # 导入数据集并转成方便作图的格式 Dataset = pd.read_csv('data/Drugs.csv') group = Dataset.groupby(['YYYY','State']).agg('sum').reset_index() df = group.pivot(index='YYYY', columns='State', values='DrugReports').reset_index() df
State YYYY KY OH PA VA WV 0 2010 10453 19707 19814 8685 2890 1 2011 10289 20330 19987 6749 3271 2 2012 10722 23145 19959 7831 3376 3 2013 11148 26846 20409 11675 4046 4 2014 11081 30860 24904 9037 3280 5 2015 9865 37127 25651 8810 2571 6 2016 9093 42470 26164 10195 2548 7 2017 9394 46104 27894 10448 1614
# fig = plt.figure() # ax = fig.add_subplot(111) #上面两行更简洁的替代方法,获取到fig,以后可以做figure级别的调用,如fig.savefig('yourfilename.png') fig, ax = plt.subplots() colors = ['grey', 'grey', 'orange', 'grey', 'grey'] lws = [2, 2, 4, 2, 2] ax.set_title(label="Evolution of PA vs other states", loc='left', color='orange') ax.set_ylabel('DrugReports') ax.grid() for col, color, lw in zip(df.columns[1:], colors, lws): ax.plot(df['YYYY'], df[col], color=color, lw=lw) ax.annotate(col, (2017, df[col].iloc[-1]), fontsize=6)
2.分别用一组长方形柱和填充面积的方式模仿画出下图,函数 y = -1 * (x - 2) * (x - 8) +10 在区间[2,9]的积分面积
x = np.linspace(0, 10, 100) y = -1 * (x -2) * (x - 8) + 10 fig, (ax1, ax2) = plt.subplots(1, 2) ax1.set_ylim(0, 20) ax1.set_xticks(range(0, 12, 2)) ax1.plot(x, y, color='red') ax2.set_ylim(0, 20) ax2.set_xticks(range(0, 12, 2)) ax2.plot(x, y, color='red') ax1.bar(x[20:], y[20:], alpha=0.5, width=0.04, color='grey', lw=0.05) ax2.bar(x[20:], y[20:], alpha=0.5, width=0.1, color='grey', lw=0.05)