如何在折线图中创建多条线?

问题描述 投票:0回答:1

我想根据年份绘制 3 个折线图(每个类别 1 个)。 我根据数据集中的行名称命名 y 轴,但这是不正确的。我应该如何定义命名以从数据集中提取数据?

from bokeh.plotting import figure
from bokeh.io import output_file, output_notebook, show
from bokeh.layouts import column
from bokeh.models import HoverTool, ColumnDataSource

data = pd.read_csv('saving.csv',dtype={'year': object})
data.head()

data['financial_year']=pd.to_datetime(data['financial_year'])

p.line(x= data.financial_year, y = data.rent)
p.line(x= data.financial_year, y = data.entertainment)

show(p)

# create a new plot with a title and axis labels
p = figure(title="Monthly expenditure", x_axis_type='datetime', x_axis_label="financial year", y_axis_label="expenses")

# add a line renderer with legend and line thickness
p.line(x, y, legend_label="expenses", line_width=2)

# Plot date along the x axis and price along the y axis
p.line(data['financial_year'], data['rent'], line_color='green')
p.line(data['financial_year'], data['entertainment'], line_color='blue')

# show the results
show(p)

pandas bokeh
1个回答
0
投票

下面是一个最小的工作示例,其中一张图中包含三行数据。我建议将 DataFrame 转换为 ColumnDataSource 以处理图中的数据。如果您想要多个数字,可以将相同的源传递给不同的数字。对线条的调用保持不变,除了名称(在我的示例中

p
)应该针对每个图形进行更改。

import pandas as pd
from io import StringIO
from bokeh.plotting import show, figure, output_notebook
from bokeh.models import ColumnDataSource
output_notebook()

data = """financial_year,2022,2021,2020,2019
rent,1000,1000,1000,1000
entertainment,2434,2343,1232,980
saving,200,200,200,200
"""

df = pd.read_csv(StringIO(data), index_col=[0]).T
df.index.name = df.columns.name
df.columns.name = None
df.index = pd.to_datetime(df.index)

>>>             rent  entertainment  saving
financial_year                             
2022-01-01      1000           2434     200
2021-01-01      1000           2343     200
2020-01-01      1000           1232     200
2019-01-01      1000            980     200


# bokeh section starts here
s = ColumnDataSource(df)

p = figure(
    title="Monthly expenditure",
    x_axis_type='datetime',
    x_axis_label="financial year",
    y_axis_label="expenses in $"
)
p.line(x='financial_year', y='rent', source=s, legend_label='rent')
p.line(x='financial_year', y='entertainment', source=s, legend_label='entertainment', color='green')
p.line(x='financial_year', y='saving', source=s, legend_label='saving', color='red')
show(p)

我希望这对您有帮助。如果没有,请尝试更新您的问题以使问题更清楚。

© www.soinside.com 2019 - 2024. All rights reserved.