[英]Line graph not propper in python bokeh after using group by
在代码使用组后,线图不是python散景中的propper
newData = data.groupby([data.OrderDate.dt.year, 'Category'])['Sales'].sum().reset_index()
df = newData #pd.DataFrame.from_dict(data)
df['OrderDate'] = pd.to_datetime(df['OrderDate'])
df = df.sort_values(by='OrderDate')
categories = df['Category'].unique()
p = figure(x_axis_type="datetime")
for cat, color in zip(categories, Spectral3):
df_line = df.loc[df['Category'] == cat]
p.line(x='OrderDate', y='Sales', line_width=2, source=df_line, legend=cat, color=color)
p.legend.click_policy="hide"
show(p)
使用的数据是这个
OrderDate Category Sales
0 2014 Furniture 82832.5164
1 2014 Office Supplies 86661.4220
2 2014 Technology 109617.4640
3 2015 Furniture 84801.7080
4 2015 Office Supplies 63019.8670
5 2015 Technology 82248.2500
6 2016 Furniture 85607.4175
7 2016 Office Supplies 82121.6480
8 2016 Technology 96572.8750
9 2017 Furniture 100269.3538
10 2017 Office Supplies 125699.4660
11 2017 Technology 140890.0350
但问题是线图看起来不像线图那么糟糕。
from bokeh.models import ColumnDataSource
from bokeh.plotting import figure
from bokeh.io import show
p = figure(x_range = (df['OrderDate'].unique().min(),df['OrderDate'].unique().max()) , y_range = (50000, df['Sales'].max() + 50000), plot_height =500, plot_width = 500)
colorlist = ['red', 'orange','green']
for cat, color in zip(df['Category'].unique(), colorlist):
data = df[df['Category'] == cat].to_dict(orient = 'list')
source = ColumnDataSource(data = data)
p.line(x = 'OrderDate', y = 'Sales', source = source, color = color, line_width=2)
show(p)
这将为每个类别在同一图表中生成3行。 Bokeh喜欢将数据作为dicts传入,因此您必须创建要绘制的数据的dict,然后将其传递给ColumnDataSource
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.