3条线的散景线图

时间:2019-05-24 12:23:10

标签: python pandas graph bokeh

我有一个不同年份和月份的数据,希望根据类别在3条线图中显示,并且X轴将是(jan,feb ....... dec)Y轴销售量。我很迷茫,因为我是Bokeh的新手,Python可以帮助我吗?

import pandas as pd
from bokeh.plotting import figure, output_file, show
from bokeh.models import ColumnDataSource
from datetime import datetime
from bokeh.palettes import Spectral3

output_file('output.html')

df = pd.read_csv('sample.csv')
p = figure(x_axis_type="date")
p.line(x=df.date, y=df.sales, line_width=2)

show(p)

这是我的数据。

enter image description here

1 个答案:

答案 0 :(得分:0)

您必须将“日期”列的内容转换为“日期”。 Pandas和Bokeh不知道这些值是日期,如果您忘记这样做,它们会像字符串一样对待。另外,x_axis_type应该是datetime而不是date。

import pandas as pd
from bokeh.plotting import figure, show
from bokeh.palettes import Spectral3

data = {'Date': ['08-11-2016', '08-11-2016', '12-06-2016', '11-08-2015', '11-10-2015', '09-06-2014', '09-02-2014', '09-01-2014', '09-06-2014', '09-03-2014', '09-05-2014', '09-07-2014', '15-04-2017', '05-12-2016', '22-09-2015', '26-12-2015', '02-01-2015', '02-01-2015', '28-10-2016'],
'Sales': [261.96, 731.94, 14.62,957.5775, 22.368, 48.68, 7.28, 907.152, 18.504, 114.9, 1706.184, 911.424, 15.552, 407.976, 68.81, 2.544, 665.88, 55.5, 8.56],
'Category': ['Furniture', 'Furniture', 'Office Supplies', 'Furniture', 'Office Supplies', 'Furniture', 'Office Supplies', 'Technology', 'Office Supplies', 'Office Supplies', 'Furniture', 'Technology', 'Office Supplies', 'Office Supplies', 'Office Supplies', 'Office Supplies', 'Office Supplies', 'Office Supplies', 'Office Supplies']}
df = pd.DataFrame.from_dict(data)
df['Date'] = pd.to_datetime(df['Date'])
df = df.sort_values(by='Date')
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='Date', y='Sales', line_width=2, source=df_line, legend=cat, color=color)
p.legend.click_policy="hide"
show(p)

enter image description here

(还绘制了技术和办公用品,由于x范围/颜色短,很难看到它们)