python数据分析—基于matplotlib绘制直方图和折线图

在同一张图上绘制直方图和折线图,并标明图例

#@author csdn NikoHsu
import matplotlib
import matplotlib.pyplot as plt
import numpy as np

matplotlib.rcParams['font.sans-serif'] = ['SimHei']  #用黑体显示中文
#输入数据
n=30
x = np.arange(n)
y = [12.2697,9.3896,8.4593,8.5168,8.5953,10.6009,10.5270,12.6960,11.9365,12.4471,12.6960,12.3280,14.0360,12.0445,12.4471,12.0996,12.6324,11.3442,11.7289,
     12.2697,11.2094,9.8945,9.9557,10.0000,10.0000,14.3034,15.0000,15.0000,15.0000,15.0000]
y2 = [2,3,3,3,3,2,2,3,3,3,2,2,2,2,2,2,3,3,2,2,2,3,3,3,3,2,2,2,2,2]
y3 = [4*i for i in y2]

# 绘柱状图
plt.bar(x+0.5, height=y, label='单位时间发车间隔',width = 0.5, facecolor='#9999ff',edgecolor='white')
plt.xlim((0,30))
plt.xticks([0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30],
           ['6:30','7:30','8:30','9:30','10:30','11:30','12:30','13:30','14:30','15:30','16:30','17:30','18:30','19:30','20:30','21:30'])
plt.yticks(np.arange(0,16,2))

# y轴设置名称
plt.ylabel("单位时段发车间隔")
# 显示图例
plt.legend()
# 画折线图
plt.plot(x, y3, "r", ms=8, marker='*',label="理想发车次数")
# 在折线图上显示具体数值, ha参数控制水平对齐方式, va控制垂直对齐方式
for x1, yy in zip(x, y2):
    plt.text(x1, 4*yy +0.2, str(yy), ha='center', va='bottom', fontsize=10, rotation=0)
plt.legend(loc="upper left")
plt.show()



最后绘制如图:python数据分析—基于matplotlib绘制直方图和折线图_第1张图片

你可能感兴趣的:(python,数据可视化)