
导入模块:
%matplotlib notebook
import numpy as np
import matplotlib.pyplot as plt
设置中文黑体:
plt.rcParams["font.sans-serif"] = ["SimHei"]
plt.rcParams["axes.unicode_minus"] = False
准备数据:
建一个labels作图的x轴文本标签
x_data = np.arange(1,8,1)
y_data = [44.98, 45.02, 44.32, 41.05, 42.08, 42.08, 42.08] # 周末休市
labels=['周一','周二','周三','周四','周五','周六','周日']
创建画布和坐标系:
在距画布顶部 0.2、左侧 0.2 的位置上添加一个宽度为 0.5、高度为0.5的绘图区域
ax = plt.axes((0.2,0.2, 0.5,0.5))
绘图:
ms: 设置圆点大小
ax.plot(labels,y_data,'.-',color='purple',ms=25)
定制刻度:
direction:(in/out/inout)分别为里,外,里和外 ,三种刻度方式
labelrotation:标签文本的旋转角度
ax.xaxis.set_tick_params(direction='in',length=8,width=2,labelrotation=25) # 单独控制
ax.yaxis.set_tick_params(direction='in',length=8,width=2)
设置轴标签:
rotation:标签文本的旋转角度
labelpad:图和文本之间的距离
ax.set_ylabel('收盘价(¥)',rotation=0,labelpad=38,fontsize=15)
ax.set_xlabel('周日期',labelpad=20,fontsize=15)
隐藏上轴脊和右轴脊:
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
整体代码如下:
# matplotlib中文网 https://www.matplotlib.org
# 需求一:绘制某股票一周内收盘价折线图(见运行结果展示图)
%matplotlib notebook
import numpy as np
import matplotlib.pyplot as plt
# 0.设置中文黑体
plt.rcParams["font.sans-serif"] = ["SimHei"]
plt.rcParams["axes.unicode_minus"] = False
# 1.准备数据
x_data = np.arange(1,8,1)
y_data = [44.98, 45.02, 44.32, 41.05, 42.08, 42.08, 42.08] # 周末休市
labels=['周一','周二','周三','周四','周五','周六','周日']
# 2.创建画布和坐标系
ax = plt.axes((0.2,0.2, 0.5,0.5))
# 3.绘图
ax.plot(labels,y_data,'.-',color='purple',ms=25)
# 4.定制刻度
ax.xaxis.set_tick_params(direction='in',length=8,width=2,labelrotation=25) # 单独控制
ax.yaxis.set_tick_params(direction='in',length=8,width=2)
# 5.设置轴标签
ax.set_ylabel('收盘价(¥)',rotation=0,labelpad=38,fontsize=15)
ax.set_xlabel('周日期',labelpad=20,fontsize=15)
# 6.隐藏上轴脊和右轴脊
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
# 7.展示图表
plt.show()
运行结果如图:

本文介绍了使用Python的matplotlib库绘制股票一周收盘价折线图的过程,包括数据准备、坐标系设置、绘图、刻度定制和轴标签设置等步骤。
8804

被折叠的 条评论
为什么被折叠?



