Matplotlib绘制条形图和折线图的组合

17
我想在一个图表中同时绘制柱形图和折线图。当我绘制柱形图时,它显示正确(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 有什么想法可以解决这个问题吗?

只需调整绘图的x轴限制即可。 - GWW
2个回答

28

你需要使用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

未来提问请附上您的数据框。


7
尝试交换绘图的顺序:
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())

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接