Home > Software engineering >  Plotting negative values in a left-right matter
Plotting negative values in a left-right matter

Time:10-13

I have the following dataframe:

Emotions = {'Student Status': ["Bachelor's Degree", "Master's Degree", "Doctoral Degree"],'ESS': [-0.058816, -0.015943, -0.018041]}
dfEmotions = pd.DataFrame(data=Emotions)

When I plot it:

dfEmotions.plot.barh(xlabel=dfEmotions['Student Status'], figsize=(30,10), legend=True)

I get the following plot:

enter image description here

But I want the plot to have the following attributes:

  • X-Axis should lead to the right (as for positive values) -> I tried using tick.right() but I think I got the syntax wrong
  • On the y-axis instead of 0,1,2 there should be the different degrees (I think it takes the indices)
  • Lastly, the bars should be colored in differently, something like red for the lowest and green for the highest e.g.

Anyone any idea?

Thanks!

CodePudding user response:

You might consider using seaborn.barplot() here. Hope that inverting x-axis was what you wanted:

import pandas as pd
import seaborn as sns

Emotions = {'Student Status': ["Bachelor's Degree", "Master's Degree", "Doctoral Degree"],'ESS': [-0.058816, -0.015943, -0.018041]}
dfEmotions = pd.DataFrame(data=Emotions)
dfEmotions.sort_values(by='ESS', ascending=False, inplace=True)  # sort by ESS
g = sns.barplot(x='ESS', 
                y='Student Status', 
                data=dfEmotions, 
                orient='h',
                palette='RdYlGn_r')  # red-yellow-green-reversed palette
g.invert_xaxis()  # invert x-axis to make bars go right

Output: enter image description here

CodePudding user response:

You can create the figure in matplotlib by inverting the x-axis and specifying three different colors like this:

import matplotlib.pyplot as plt   

plt.figure()
    plt.barh(dfEmotions['Student Status'], dfEmotions['ESS'], color=['C0', 'C3', 'C2'])
    plt.gca().invert_xaxis()
  • Related