简体   繁体   中英

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. 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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