Student NL
Student NL

Reputation: 429

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 enter image description here

and the following plot is generated:

enter image description here

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:

enter image description here

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.

Upvotes: 0

Views: 1654

Answers (1)

mozway
mozway

Reputation: 262614

I don't have the issue, running your code:

bar + line

That said, an easy fix is to run ax.set_xlim(-0.5, 4.5)

Upvotes: 2

Related Questions