1

I am trying to plot two overlay bar plots over 4 different categories. My dataset looks something like:

category count_first count_second
    a          15         80
    b          18         50
    c          12         99
    d          11         30

I am trying to plot a bar plot for both count_first, as well as count second whilst perserving the bar order by count. If not ordered, I can simply plot this with dataframe.melt('category')... but I am having problems with the case, where the bars need to be ordered.

df = df.sort_values(by=['category'])
m_categories=reversed(list(df['category']))
df['category'] = pd.Categorical(df['category'],categories=m_categories, ordered=False)
print(df)

#df2 = df.melt('category') -- DOESNT work

gx = (ggplot(df)
      + geom_col(aes('category','count_first', fill="#FFCE33"),stat="identity") + theme_classic()
      + geom_col(aes('category','count_second'),stat="identity")
      + xlab("category")
      + ylab("counts")
      + theme(axis_text=element_text(size=12,angle=70),
              axis_title=element_text(size=15))
)
gx.draw()
plt.show()

I cant seem to set the fill parameter for individual geom_col objects, how can this be done?

sdgaw erzswer
  • 2,182
  • 2
  • 26
  • 45
  • fill="#FFCE33" should be outside of the `aes` brackets. You are better melting into a single column though as this is more of the ggplot way of doing things: https://stackoverflow.com/questions/9531904/plot-multiple-columns-on-the-same-graph-in-r – Michael Harper Mar 05 '18 at 13:59
  • Single column works perfectly, but I cant reorder x-axis that way. – sdgaw erzswer Mar 05 '18 at 14:24

2 Answers2

1
import pandas as pd
from plotnine import *
from io import StringIO

sio = StringIO("""
category count_first count_second
    a          15         80
    b          18         50
    c          12         99
    d          11         30
""")

df = pd.read_csv(sio, sep='\s+')
df = pd.melt(df, 'category', var_name='count_type')

gx = (ggplot(df)
      + geom_col(aes('category', 'value', fill='count_type'), stat='identity')
      + labs(y='counts')
      + theme_classic()
)

enter image description here

has2k1
  • 2,095
  • 18
  • 16
0
import matplotlib.pyplot as plt
import numpy as np
a = [15, 80,0]
b = [18, 50,0]
c = [12, 99,0]
d = [11,30,0]
ax = plt.subplot(111)
w = 0.3
count = np.array([1.1,2.1,0]
ax.bar(x-w, a,width=w,color='b',align='center')
ax.bar(x, b,width=w,color='r',align='center')
ax.bar(x+w, c,width=w,color='g',align='center')
ax.bar(x+w+w, d,width=w,color='y',align='center')
plt.show()