Python matplotlib 绘制条形图和折线图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38810009/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 21:27:22  来源:igfitidea点击:

matplotlib plot bar and line charts together

pythonpython-2.7pandasmatplotlib

提问by Steve

I want to plot bar and line together in one chart. When I plot bars, it displays correctly(g1 and g10 are displayed completed):enter image description here

我想在一张图表中绘制条形图和线条。当我绘制条形图时,它显示正确(g1 和 g10 显示完成):在此处输入图片说明

However, if I add a line to the plot:

但是,如果我在图中添加一条线:

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

The bar chart is incomplete as below(g1 and g10 are chopped): enter image description here

条形图不完整如下(g1和g10被切碎): 在此处输入图片说明

Any idea how to fix this problem?

知道如何解决这个问题吗?

回答by Serenity

You have to expand x axis with xlim:

您必须使用 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

在此处输入图片说明

For future question post your dataframe.

对于未来的问题,请发布您的数据框。

回答by Happy001

Try switching the order of plotting:

尝试切换绘图顺序:

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

or preserve the original barchart xlim:

或保留原始条形图xlim

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