微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

散景:根据分类数据绘制多条线

如何解决散景:根据分类数据绘制多条线

我想绘制多条线,每条线代表数据集中的一个类变量,并为每条线指定不同的颜色。我使用的数据框如下所示。我想使用 ColumnDataSource 和 multi_line 为每个国家/地区绘制一条线。数据集几乎涵盖了世界上所有国家,因此将它们一一绘制起来太费力了。

         Entity  Code  Year  TWh Oil
0        Belgium  BEL  1965  111 1500
1        Belgium  BEL  1966  310 650
2        Belgium  BEL  1967  80  345
3        France   FRA  1965  200 768
4        France   FRA  1966  199 972 

我刚刚开始学习编程和散景,我似乎无法理解 DataCamp 中提供的内容。我已经阅读了 multi_line 上的文档,它说它需要 x 和 y 坐标的“列表列表”。但是,我不知道该怎么做,因为 datacamp 只解释了如何为 ColumnDataSource 中的 x 和 y 坐标选择列。如果有人能在这里进一步帮助我,将不胜感激!这是我现在使用的代码(我大部分都理解)。

from bokeh.io import show,output_file
from bokeh.plotting import figure,ColumnDataSource,curdoc
from bokeh.palettes import Spectral6
from bokeh.layouts import row,column,widgetBox
from bokeh.models import HoverTool,Select,Slider,CategoricalColorMapper
import pandas as pd
from datetime import date
import numpy as np

#import datasets
df = pd.read_csv('nuclear-energy-generation.csv')
df_fossil_production = pd.read_csv('fossil-fuel-production.csv')
df = df.rename(columns={"Electricity from nuclear (TWh)": "TWh"})

#Filter for few countries for simplicity (temporary)
df = df.loc[df['Entity'].isin(["Netherlands",'France','Belgium','Germany','Spain'])]
df_fossil_production = df_fossil_production.loc[df_fossil_production['Entity'].isin(["Netherlands",'Spain'])]

df_merge = pd.merge(df,df_fossil_production,on=["Entity","Code","Year"],how = 'outer')
df_merge['Oil'] = np.random.choice([111,200,15,60,300,400,266,167,566,80,69,77,277,288,199,310],df_merge.shape[0])

source = ColumnDataSource(data={
    'x' : df_merge.Year,'y' : df_merge.TWh})

xmin,xmax = min(df_merge.Year),max(df_merge.Year)
ymin,ymax = min(df_merge.TWh),max(df_merge.TWh)

country_list = df_merge.Entity.unique().tolist()
color_mapper = CategoricalColorMapper(factors=country_list,palette=Spectral6)

#create figure for line
p = figure(title="Power generation",plot_width=1000,plot_height=500,#x_axis_type='datetime'
            x_range=(xmin,xmax),y_range=(ymin,ymax))

p.line(x = 'x',y = 'y',source = source,legend='Entity')

#multi_line does not work :(
#p.multi_line(xs = 'x',ys = 'y',legend_label='Entity')

p.legend.location = 'top_left'
p.xaxis.axis_label = "Year"
p.yaxis.axis_label = "Power generation (TWh)"

def callback (attr,old,new):
    y = select.value
    
    p.yaxis.axis_label = y
    
    new_data = {
        'x' : df_merge.Year,'y' : df_merge[y]}
    source.data = new_data
    
select = Select(options=['TWh','Oil'],value='TWh',title='y-axis data')

select.on_change('value',callback)

layout = row(widgetBox(select),p)
curdoc().add_root(layout)
output_file('line.html')
show(layout) 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。