matplotlib打印条形图和折线图

2024-09-29 09:32:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我想把条形图和直线画在一张图表上。当我绘制条形图时,它会正确显示(g1和g10显示完毕):enter image description here

但是,如果我在绘图中添加一行:

m1_t[['abnormal','fix','normal']].plot(kind='bar')
m1_t['bad_rate'].plot(secondary_y=True)

条形图不完整,如下所示(g1和g10被截断): enter image description here

知道怎么解决这个问题吗?


Tags: 绘图plot图表绘制barfix直线bad
2条回答

必须使用xlim展开x轴:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

width = .35 # width of a bar

m1_t = pd.DataFrame({
 'abnormal' : [90,40,30,30,30,25,25,20,15,10],
 'fix' : [60,70,65,70,70,60,50,45,45,45],
 'normal' : [140,160,170,180,190,200,210,220,230,240],
 'bad_rate' : [210,100,100,70,70,75,70,60,65,60]})

m1_t[['abnormal','fix','normal']].plot(kind='bar', width = width)
m1_t['bad_rate'].plot(secondary_y=True)

ax = plt.gca()
plt.xlim([-width, len(m1_t['normal'])-width])
ax.set_xticklabels(('G1', 'G2', 'G3', 'G4', 'G5', 'G6', 'G7', 'G8', 'G9', 'G10'))

plt.show()

enter image description here

为以后的问题张贴你的数据帧。

尝试切换绘图顺序:

ax = m1_t['bad_rate'].plot(secondary_y=True)
m1_t[['abnormal','fix','normal']].plot(kind='bar', ax=ax)

或者保留原始条形图xlim

ax = m1_t[['abnormal','fix','normal']].plot(kind='bar')
m1_t['bad_rate'].plot(secondary_y=True, xlim=ax.get_xlim())

相关问题 更多 >