How do I create multiple lines in a line chart?

33 Views Asked by At

I would like to plot 3 line charts (1 for each category) against the year. I name the y-axis based on the row names in the data set but it is incorrect. How should I define the naming to pull the data from the dataset?

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)

data set

1

There are 1 best solutions below

2
mosc9575 On

Below is a minimal working example with your data with three lines in one figure. I suggest to transform your DataFrame into a ColumnDataSource to address the data in the plot. If you want multiple figures, you can pass the same source to different figures. The call for the lines keeps the same except the name (in my example p) should change for each figure.

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)

basic plot with three lines

I hope this helps you. If not please try to update your question to make the problem clearer.