Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send axhline to back of Matplotlib's barplot

I have the following code. It uses Matplotlib wrapper in Pandas:

import pandas as pd
import io
import matplotlib
import matplotlib.pyplot as plt

test=u"""Cell,Value
Bcells,0.056304
DendriticCells,0.3155388
Macrophages,0.131430
"""

tableau10=[ "#17BECF", "#BCBD22", "#7F7F7F", ]

toplot_df = pd.read_csv(io.StringIO(test))
toplot_df.set_index('Cell',inplace=True)
xlabels =  toplot_df.index.values
barplot   = toplot_df.plot(kind="bar", figsize=(17,17), \
                          color = tableau10, \
                          width=0.7,\
                          fontsize = 30,\
                          legend=False,
                          ylim = (0,0.5),
                          subplots=False)

ax = plt.gca()
ax.set_xticklabels(xlabels, rotation=30, ha='right')

# How to to make this to the back
plt.axhline(y=0.1, linewidth=1, color='r',zorder=1)
plt.xlabel("")
plt.ylabel("Score", fontsize=30, fontweight="bold")

And it makes this figure:

enter image description here

As stated there. How can I make the axhline to the background? I tried zorder but won't work.

like image 447
neversaint Avatar asked May 24 '16 10:05

neversaint


1 Answers

You just need to make the zorder of the barplot higher than the zorder of the axhline. In your example, I just had to add the option zorder=2 to the barplot = toplot_df.plot() call.

import pandas as pd
import io
import matplotlib
import matplotlib.pyplot as plt

test=u"""Cell,Value
Bcells,0.056304
DendriticCells,0.3155388
Macrophages,0.131430
"""

tableau10=[ "#17BECF", "#BCBD22", "#7F7F7F", ]

toplot_df = pd.read_csv(io.StringIO(test))
toplot_df.set_index('Cell',inplace=True)
xlabels =  toplot_df.index.values
barplot   = toplot_df.plot(kind="bar", figsize=(17,17), \
                          color = tableau10, \
                          width=0.7,\
                          fontsize = 30,\
                          legend=False,
                          ylim = (0,0.5),
                          subplots=False,
                          zorder=2)                         ##### This is all I added

ax = plt.gca()
ax.set_xticklabels(xlabels, rotation=30, ha='right')

# How to to make this to the back
plt.axhline(y=0.1, linewidth=1, color='r',zorder=1)
plt.xlabel("")
plt.ylabel("Score", fontsize=30, fontweight="bold")

plt.show()

enter image description here

like image 155
tmdavison Avatar answered Sep 30 '22 03:09

tmdavison