简体   繁体   English

在 matplotlib 中组合条形图和线图而不移动条形图

[英]Combining a bar plot and a line plot in matplotlib without shifting the bar plot

I am looking for a way to combine a bar and a line plot, without the bar plot shifting when the line plot is added.我正在寻找一种结合条形图和线形图的方法,而在添加线形图时条形图不会移动。

The following code is used to generate the barplot以下代码用于生成条形图

import matplotlib.pyplot as plt
import pandas as pd
data = pd.DataFrame([[4,30,0,3,2,2,], [5,24,0,3,1,1,], [6,34,0,4,2,1], [7,18,0,2,1,1], [8,34,0,3,3,2]], columns=['t', 'Cost', 0,1,2,3])
data[[1,2,3]].plot(kind='bar')

Thus, the data looks as follows因此,数据如下所示在此处输入图像描述

and the following plot is generated:并生成以下图:

在此处输入图像描述

Next, I add the cost information using接下来,我使用添加成本信息

data['Cost'].plot(style='o--', c='black', secondary_y=True)

Running it all together returns the following graph:一起运行它会返回下图:

在此处输入图像描述

The issue is that the outer bars are no longer visible.问题是外部条不再可见。 I tried changing the range on the x-axis with xlim, but that did not help, it only made it worse.我尝试用 xlim 更改 x 轴上的范围,但这并没有帮助,只会让情况变得更糟。 There is probably an easy fix for it, which I have not been able to find anywhere online.可能有一个简单的解决方法,我无法在网上找到任何地方。

I don't have the issue, running your code:我没有问题,运行您的代码:

条+线

That said, an easy fix is to run ax.set_xlim(-0.5, 4.5)也就是说,一个简单的解决方法是运行ax.set_xlim(-0.5, 4.5)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM