0

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.

1 Answer 1

2

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)

Sign up to request clarification or add additional context in comments.

2 Comments

Interesting, because I do have this issue. Could it be due to any of the default settings related to plotting, because I do not get the figure you showed.
I forgot, if ax is not defined use plt.gca().set_xlim(...)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.