绘制折线图
import matplotlib.pyplot as plt
squares = [1, 4, 9, 16, 25, 100]#创建了一个用来制作图表数据的列表
fig, ax = plt.subplots()#调用函数subplots(),这个函数可在一张图片中绘制一个或多个图片。变量fig表示整张图片,变量ax表示图片中的各个图表。
ax.plot(squares)#调用方法plot(),它尝试根据给定的数据以有意义的方式绘制图表
plt.show()
![](https://img.haomeiwen.com/i27560883/cf62299a8a2fca9d.png)
- 修改细节
import matplotlib.pyplot as plt
input_values = [1, 2, 3, 4, 5, 10]#X轴
squares = [1, 4, 9, 16, 25, 100]#Y轴
fig, ax = plt.subplots()
ax.plot(input_values, squares, linewidth=3)
ax.set_title("figure1", fontsize=20)
ax.set_xlabel("x value", fontsize=14)
ax.set_ylabel("y value", fontsize=14)
ax.tick_params(axis='both', labelsize=14)#设置刻度标记的大小
plt.show()
![](https://img.haomeiwen.com/i27560883/91cb3e47ef047c3f.png)
使用plot()
时可以指定各种实参,还可使用众多函数对图形进行定制。
- matplotlib中有许多内置样式可以使用
plt.style.available
['Solarize_Light2',
'_classic_test_patch',
'_mpl-gallery',
'_mpl-gallery-nogrid',
'bmh',
'classic',
'dark_background',
'fast',
'fivethirtyeight',
'ggplot',
'grayscale',
'seaborn',
'seaborn-bright',
'seaborn-colorblind',
'seaborn-dark',
'seaborn-dark-palette',
'seaborn-darkgrid',
'seaborn-deep',
'seaborn-muted',
'seaborn-notebook',
'seaborn-paper',
'seaborn-pastel',
'seaborn-poster',
'seaborn-talk',
'seaborn-ticks',
'seaborn-white',
'seaborn-whitegrid',
'tableau-colorblind10']
可以直接调用内置样式:
import matplotlib.pyplot as plt
input_values = [1, 2, 3, 4, 5, 10]
squares = [1, 4, 9, 16, 25, 100]
fig, ax = plt.subplots()
plt.style.use('fivethirtyeight')
ax.plot(input_values, squares)
plt.show()
散点图
import matplotlib.pyplot as plt
input_values = [1, 2, 3, 4, 5, 10]
squares = [1, 4, 9, 16, 25, 100]
fig, ax = plt.subplots()
plt.style.use('seaborn')
ax.scatter(input_values, squares)
plt.show()
- 自动计算数据
x_values = range(1, 1001)
y_values = [x**2 for x in x_values]
plt.style.use('seaborn')
fig, ax = plt.subplots()
ax.scatter(x_values, y_values, s=10, ax.scatter(x_values, y_values, s=5, c=(0.1, 0.3, 0.4))#参数s设置绘制图形时使用的点的尺寸
ax.axis([0, 1100,0, 1100000])
plt.show()
参数c定义颜色, 可以直接c = 'red'
,也可以用RGB颜色,值越接近0,指定的颜色越深;值越接近1,指定的颜色越浅。
![](https://img.haomeiwen.com/i27560883/08eed0f6c7dfe331.png)
- 也可以使用颜色映射(colormap)
颜色映射是一系列颜色,从起始颜色渐变到结束颜色。在可视化中,颜色映射用于突出数据的规律。
ax.scatter(x_values, y_values, s=5, c=y_values, cmap=plt.cm.Blues)#其余步骤不变
将c值设置成了一个y值列表,并使用参数cmap告诉pyplot使用哪个颜色映射。
要了解pyplot中所有的颜色映射,应访问Matplotlib网站主页-Examples-Color-Colormaps reference
-自动保存图表
plt.savefig('xxx.png', bbox_inches='tight')
这个文件将储存在script所在的目录。第二实参指定图表多余的空白区域裁剪掉。
网友评论