本节你将学到
绘制折线图绘制散点图调整曲线的颜色、粗细调整图标标签绘制简单折线图
折线图的绘制,需要用到matplotlib.pyplot库,利用其中的plot()方法实现折线图的绘制。
import matplotlib.pyplot as pltinput_values=[1,2,3,4,5]squares = [1,4,9,16,25]plt.plot(squares)plt.show()
上面画出了输入数值为[1,2,3,4,5],输出数值为其平方的折线图。但是缺少相应的标签来说明图的情况。
修改标签
plt.plot(squares,linewidth=5)# 以下代码设置了图标的标题并给坐标轴加上标签。plt.title("Square Numbers",fontsize=24)plt.xlabel("Value",fontsize=14)plt.ylabel("Square of Value",fontsize=14)plt.tick_params(axis='both',labelsize=14)plt.show()
散点图的绘制
散点图的绘制,需要用到matplotlib.pyplot库,利用其中的scatter()方法实现散点图的绘制。
x_values=[1,2,3,4,5]y_values=[1,4,9,16,25]# 参数s控制散点图中点的大小plt.scatter(x_values,y_values,s=100)plt.title("Square Numbers",fontsize=24)plt.xlabel("Value",fontsize=14)plt.ylabel("Square of Value",fontsize=14)plt.tick_params(axis='both',labelsize=14)plt.show()
如果需要根据x_values的值自动计算纵坐标值,可以采用以下方法
# 自动计算纵坐标值x_values=list(range(1,500))y_values=[x**2 for x in x_values]# 参数s控制散点图中点的大小plt.scatter(x_values,y_values,s=10)plt.title("Square Numbers",fontsize=24)plt.xlabel("Value",fontsize=14)plt.ylabel("Square of Value",fontsize=14)plt.tick_params(axis='both',labelsize=14)plt.show()
如果想自定义颜色,可以在scatter()中增加参数c
# 自动计算纵坐标值x_values=list(range(1,500))y_values=[x**2 for x in x_values]# 参数s控制散点图中点的大小plt.scatter(x_values,y_values,c='red',s=10)plt.title("Square Numbers",fontsize=24)plt.xlabel("Value",fontsize=14)plt.ylabel("Square of Value",fontsize=14)plt.tick_params(axis='both',labelsize=14)#控制横纵坐标的范围plt.axis([0,600,0,360000])plt.show()
如果觉得单一颜色不好看,可以使用渐变色。渐变色的本质上需要利用纵坐标的数值进行颜色映射
x_values=list(range(1,500))y_values=[x**2 for x in x_values]# 参数s控制散点图中点的大小plt.scatter(x_values,y_values,c=y_values,cmap=plt.cm.Blues,s=10)plt.title("Square Numbers",fontsize=24)plt.xlabel("Value",fontsize=14)plt.ylabel("Square of Value",fontsize=14)plt.tick_params(axis='both',labelsize=14)#控制横纵坐标的范围plt.axis([0,600,0,360000])plt.show()
更多精彩
如果觉得《Python绘制简单折线图 散点图》对你有帮助,请点赞、收藏,并留下你的观点哦!