嗨,我试图弄清楚如何在每个国家/地区仅使用一种颜色 - 填充颜色。以下示例给出了每个国家/地区的透明和较深颜色的混合。我希望只有一种颜色。感谢帮助
import plotly
#import plotly.graph_objects as go
import plotly.express as px
df = px.data.gapminder()
fig = px.area(df, x="year", y="pop", color="country",
groupnorm='fraction')
plotly.io.write_image(fig, file='areatest.png', format='png')
最佳答案
px.area
没有任何争议这将直接为您提供单一颜色。但这不应该阻止你。只需使用:
fig.for_each_trace(lambda trace: trace.update(fillcolor = trace.line.color))
... 要得到:... 而不是默认结果,即:
完整代码:
import plotly
import plotly.express as px
df = px.data.gapminder()
df = df[df['continent']=='Americas']
fig = px.area(df, x="year", y="pop", color="country",
groupnorm='fraction')
fig.for_each_trace(lambda trace: trace.update(fillcolor = trace.line.color))
fig.show()
一些细节:px.area
将为与 color
关联的每一行分配一种颜色参数,然后将该颜色的部分透明版本应用于相应的区域/填充。如果您运行 fig.show
您可以检查第一类的颜色:Scatter({
'fillcolor': '#636efa',
'groupnorm': 'fraction',
'hovertemplate': 'country=Argentina<br>year=%{x}<br>pop=%{y}<extra></extra>',
'legendgroup': 'Argentina',
'line': {'color': '#636efa'},
在这里你只能看到'line': {'color': '#636efa'}
毫无疑问,找不到 fillcolor 会让人有点困惑。但是如果你使用 fig.full_figure_for_development
,可以看到实际上传递给javascript的fillcolor是'rgba(99, 110, 250, 0.5)'
:Scatter({
'connectgaps': False,
'error_x': {'visible': False},
'error_y': {'visible': False},
'fill': 'tonexty',
'fillcolor': 'rgba(99, 110, 250, 0.5)',
这正是您运行时要覆盖的内容:fig.for_each_trace(lambda trace: trace.update(fillcolor = trace.line.color))
关于python - Plotly:用单一颜色的填充和线条绘制面积图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66504427/