Matplotlib 使用指南
Matplotlib 是 python 世界里常用的绘图函数库,包含很多好用的方法,此处只展示几个简单的示例,更多绘图方式参见这里
示例1 - 用 Matplotlib 创建柱状图
import matplotlib.pyplot as plt
import seaborn as sns # seaborn 的载入是为了让图像更好看,通常都会搭配 matplotlib.pyplot 一同载入使用pyplot 的 bar 功能中有两个必要参数:条柱的 x 坐标和条柱的高度。
plt.bar([1, 2, 3], [224, 620, 425])可以利用 pyplot 的 xticks 功能,或通过在 bar 功能中指定另一个参数,指定 x 轴刻度标签。以下两个框的结果相同。
# 绘制条柱
plt.bar([1, 2, 3], [224, 620, 425])
# 为 x 轴指定刻度标签及其标签
plt.xticks([1, 2, 3], ['a', 'b', 'c'])# 用 x 轴的刻度标签绘制条柱
plt.bar([1, 2, 3], [224, 620, 425], tick_label=['a', 'b', 'c'])用以下方法设置轴标题和标签。
plt.bar([1, 2, 3], [224, 620, 425], tick_label=['a', 'b', 'c'])
plt.title('Some Title')
plt.xlabel('Some X Label')
plt.ylabel('Some Y Label')示例2 - 折线图(设定 x 和 y 更一般性的作图)
# 用合适的标签创建线图
y_axis = df.groupby('acidity_levels')["quality"].mean()
labels = ['Extreme', 'High', 'Moderate', 'Low acidic']
x_axis = range(len(labels))
plt.plot(x_axis, y_axis)
plt.title('Average Quality Ratings by Acidic Levels')
plt.xlabel('Acidic Levels')
plt.ylabel('Average Quality Rating');
plt.xticks(x_axis, labels); # 设定 x 轴上的标签(不是 x 轴变量的名字,而是把原先 x_axis 的每个值对应地换成相应的 label)示例3 - 柱状图(Bar chart)
# genre_counts 的类型是 Series
'''
genre_counts :
Action 57
Adventure 56
Science Fiction 41
Thriller 31
Fantasy 28
Drama 28
Family 20
Crime 15
Comedy 13
Animation 7
Mystery 7
War 4
Western 3
Romance 2
Horror 2
History 1
dtype: int64
'''
labels = list(genre_counts.index)
# 使用 pandas 自带的 .plot() 快速出图后,再用 plt 进行细节设置
genre_counts.plot(kind="bar", title="Top Popular Movie Genres");
plt.xlabel('Genre')
plt.ylabel('Movies Count');绘图
# 设置显示说明图例(legend)
plt.legend()
# 设置好各种参数后,用以下指令生成图像
plt.show()
打赏