10

I'm using pandas to plot some data.

If I plot this:

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({'a': [100, 200, 150, 175],
                   'b': [430, 30, 20, 10]})
fig, ax1 = plt.subplots(figsize=(15, 10))
df['b'].plot(kind='bar', color='y')
df['a'].plot(kind='line', marker='d')

Everything plots fine.

GoodGraph

If I plot the bar axis on the secondary axis, the bar plot will be in front of the line plots, obstructing the lines from being viewed, like this.

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({'a': [100, 200, 150, 175],
                   'b': [430, 30, 20, 10]})
fig, ax1 = plt.subplots(figsize=(15, 10))
df['b'].plot(kind='bar', color='y', secondary_y=True)
df['a'].plot(kind='line', marker='d')

SadGraph

How do I make a bar plot/line plot where...

  • Using pandas/matplotlib
  • Bar plot is on secondary axis and line chart is on primary axis
  • Line plots are in front of the bar plot
2
  • I assume that the plot() function of a Dataframe also has the zorder keyword; you could try setting that to some high value in your second example. Commented Jun 30, 2016 at 20:01
  • Hmm... Hadn't thought of that. But it still doesn't seem like it works. I can tell that it works when both are plotted on the left y-axis, but the one plotted on the right y-axis is always on top. I would really prefer to have bars on the right y axis, so my boss sees the same thing he's always seen. Commented Jun 30, 2016 at 20:15

1 Answer 1

9

you could put line on primary axis.

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({'a': [100, 200, 150, 175],
                   'b': [430, 30, 20, 10]})
fig, ax1 = plt.subplots(figsize=(15, 10))
df['b'].plot(kind='bar', color='y')
df['a'].plot(kind='line', marker='d', secondary_y=True)

enter image description here

Or, create two axes ax1 and ax2 with twinx().

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({'a': [100, 200, 150, 175],
                   'b': [430, 30, 20, 10]})
fig, ax1 = plt.subplots(figsize=(15, 10))
ax2 = ax1.twinx()
df['b'].plot(kind='bar', color='y', ax=ax1)
df['a'].plot(kind='line', marker='d', ax=ax2)
ax1.yaxis.tick_right()
ax2.yaxis.tick_left()

enter image description here

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

Comments

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.