Home > Software engineering >  Plot pandas dataframe as histogram with different colors
Plot pandas dataframe as histogram with different colors

Time:06-29

I have a pandas dataframe of the following form

df= pd.DataFrame([[1,100],[-1,50],[1,140],[1,300],[-1,400]],columns=['key','size'])

I would like to plot an histogram of the column size where in the x-axis the value of each bin is the index of each row, and the height of the histogram for a given bin is the value of df['size']. Also, I would like the bar in a given bin to be colored in red if key==-1 or green if key==1.

I know how to make plots with vertical bars - I just call df['size'].plot(kind='bar'). How can I color each bar accordingly to the value of key? I couldn't find a way to do so.

Can anyone help me?

Thanks

CodePudding user response:

You can use the following:

df['size'].plot(
    kind='bar',
    color=df['key'].replace({1:'green', -1:'red'}),
)

Output:

enter image description here

CodePudding user response:

You can easily achieve a bar plot with the bar plot

CodePudding user response:

If you are trying to make custom plots with categorical variables, I recommend you to look the seaborn library.

Seaborn is a Python data visualization library based on matplotlib. It provides a high-level interface for drawing attractive and informative statistical graphics.

enter image description here

  • Related