简体   繁体   English

更改绘图折线图中的色标

[英]change color scale in plotly line chart

I use the following function to plot one line per year of data (overlayed so that I can compare one year to the others).我使用以下函数绘制每年数据的一条线(重叠以便我可以将一年与其他年份进行比较)。 What I would like to get to is for each line to have a color defined as a gradient instead of the default color scale (ie 2008 line in light blue to 2017 line in very dark blue).我想要的是让每条线的颜色定义为渐变而不是默认色标(即 2008 年的浅蓝色线到 2017 年的深蓝色线)。

What is the correct way to do this?这样做的正确方法是什么? I've tried using the colorscale parameter (see code) but can't quite figure it out where to put it.我试过使用 colorscale 参数(见代码),但无法弄清楚把它放在哪里。

def plotPMByYear_plotly(df, minyear):
    allYears = list(set(list(df.Year)))
    allYears = [int(x) for x in allYears if str(x) != 'nan']
    data = []
    df = df[df["Year"]>=minyear]
    for year in allYears:
        yeardf = df[df["Year"] == year]
        trace = go.Scatter(
            x = yeardf['Month'],
            y = yeardf['Value'],
            mode = 'lines',
            name = year
        )
        colorscale='Jet',
        data.append(trace)
    iplot(data, filename='line-mode')

在此处输入图片说明

After a bit of digging, I found the solution as in the code below:经过一番挖掘,我找到了如下代码所示的解决方案:

from colour import Color

def plotPMByYear_plotly(df, minyear,color1,color2):
    df = df[df["Year"]>=minyear]
    allYears = list(set(list(df.Year)))
    allYears = [int(x) for x in allYears if str(x) != 'nan']
    allYears.sort()
    colors = list(Color(color1).range_to(Color(color2),len(allYears)))
    colors = ['rgb'+str(x.rgb) for x in colors]
    data = []
    i = 0

    for year in allYears:
        yeardf = df[df["Year"] == year]
        trace = go.Scatter(
            x = yeardf['Month'],
            y = yeardf['Value'],
            mode = 'lines',
            marker=dict(color=colors[i]),
            name = year
        )
        i+=1
        data.append(trace)

    layout = go.Layout(
        title = 'Year on Year comparison'
    )

    fig = go.Figure(data=data, layout=layout)  
    iplot(fig, filename='line-mode')

which would work for example with the following arguments:例如,它可以使用以下参数:

plotPMByYear_plotly(dfM, 2008,'white','red')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM