1

我正在尝试在 4 个不同的类别上绘制两个叠加条图。我的数据集看起来像:

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

我正在尝试为 count_first 和 count second 绘制条形图,同时按计数保持条形顺序。如果没有订购,我可以简单地用 dataframe.melt('category') 绘制它......但我遇到了需要订购条形的情况。

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()

我似乎无法为单个 geom_col 对象设置填充参数,如何做到这一点?

4

2 回答 2

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()
)

在此处输入图像描述

于 2018-03-07T11:39:14.787 回答
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()
于 2018-03-07T10:37:02.317 回答