8

I am plotting one column of a pandas dataframe as line plot, using plot() :

df.iloc[:,1].plot()

and get the desired result:

enter image description here

Now I want to plot another column of the same dataframe as bar chart using

ax=df.iloc[:,3].plot(kind='bar',width=1)

with the result:

enter image description here

And finally I want to combine both by

spy_price_data.iloc[:,1].plot(ax=ax)

which doesn't produce any plot.

Why are the x-ticks of the bar plot so different to the x-ticks of the line plot? How can I combine both plots in one plot?

3
  • I'm not sure why the x-ticks are different as they shouldn't be. Regarding getting a line and a bar chart on the same plot you can use subplots. I'll submit an answer Commented Sep 18, 2016 at 16:56
  • See this for your first question, it might help. Commented Sep 18, 2016 at 17:00
  • The problem of getting right xticks was solved here Commented Sep 18, 2016 at 17:48

1 Answer 1

7
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

some data

df = pd.DataFrame(np.random.randn(5,2))
print (df)
          0         1
0  0.008177 -0.121644
1  0.643535 -0.070786
2 -0.104024  0.872997
3 -0.033835  0.067264
4 -0.576762  0.571293

then we create an axes object (ax). Notice that we pass ax to both plots

_, ax = plt.subplots()

df[0].plot(ax=ax)
df[1].plot(kind='bar', ax=ax)

enter image description here

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

9 Comments

Could you please try to do the trick with this DF: df=pd.DataFrame({'v1':np.sin(np.arange(50)), 'v2':np.cos(np.arange(50)**2)}, index=pd.date_range('2016-01-01', periods=50, freq='30T')) ?
I tried this: df = pd.DataFrame(np.random.randn(5,2)) ax = plt.subplots() df[0].plot(ax=ax) df[1].plot(kind='bar', ax=ax) and got : AttributeError: 'tuple' object has no attribute 'get_figure'
@MaxU Did you try what I have above? Did it only plot one series?
@BobHaffner, yes, the second plot completely overwrites the first one
@MaxU Same here. Give this a go _, ax = plt.subplots(figsize=(75,50)) plt.plot(df.index, df['v1']) plt.bar(df.index, df['v2'], width=.01)
|

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.