我一直在试着用图九画一个堆叠的条形图。此图表示相同“类别”内的月末库存。"SubCategory“就是应该堆叠的东西。
我已经构建了一个从查询到数据库的pandas数据帧。该查询检索日期范围内“类别”内每个“子类别”的总和(库存)。
这是DataFrame的格式:
SubCategory1 SubCategory2 SubCategory3 .... Dates
0 1450.0 130.5 430.2 .... 2019/Jan
1 1233.2 1000.0 13.6 .... 2019/Feb
2 1150.8 567.2 200.3 .... 2019/Mar日期应该在X轴上,Y应该由"SubCategory1“+ "SubCategory2”+ "SubCategory3“之和确定,并且是可区分颜色的。
我试过了,因为我认为它有意义,但没有运气:
g = ggplot(df)
for key in subcategories:
g = g + geom_bar(aes(x='Dates', y=key), stat='identity', position='stack') 其中,子类别是具有subcategories名称的字典。
可能数据帧的格式不是很理想。或者我不知道如何正确地将它与plotnine/ggplot一起使用。
谢谢你的帮助。
发布于 2019-09-25 20:42:06
您需要整洁格式的数据
from io import StringIO
import pandas as pd
from plotnine import *
from mizani.breaks import date_breaks
io = StringIO("""
SubCategory1 SubCategory2 SubCategory3 Dates
1450.0 130.5 430.2 2019/Jan
1233.2 1000.0 13.6 2019/Feb
1150.8 567.2 200.3 2019/Mar
""")
data = pd.read_csv(io, sep='\s+', parse_dates=[3])
# Make the data tidy
df = pd.melt(data, id_vars=['Dates'], var_name='categories')
"""
Dates categories value
0 2019-01-01 SubCategory1 1450.0
1 2019-02-01 SubCategory1 1233.2
2 2019-03-01 SubCategory1 1150.8
3 2019-01-01 SubCategory2 130.5
4 2019-02-01 SubCategory2 1000.0
5 2019-03-01 SubCategory2 567.2
6 2019-01-01 SubCategory3 430.2
7 2019-02-01 SubCategory3 13.6
8 2019-03-01 SubCategory3 200.3
"""
(ggplot(df, aes('Dates', 'value', fill='categories'))
+ geom_col()
+ scale_x_datetime(breaks=date_breaks('1 month'))
)

发布于 2019-09-25 00:48:53
你真的需要使用plotnine吗?你只需要:
df.plot.bar(x='Dates', stacked=True)输出:

https://stackoverflow.com/questions/58084384
复制相似问题