Mau*_*sis 6 python colors bar-chart plotly plotly-python
我正在尝试为绘图条形图中的某些条形设置不同的颜色:
import plotly.express as px
import pandas as pd
data = {'Name':['2020/01', '2020/02', '2020/03', '2020/04',
'2020/05', '2020/07', '2020/08'],
'Value':[34,56,66,78,99,55,22]}
df = pd.DataFrame(data)
color_discrete_sequence = ['#ec7c34']*len(df)
color_discrete_sequence[5] = '#609cd4'
fig=px.bar(df,x='Name',y='Value',color_discrete_sequence=color_discrete_sequence)
fig.show()
Run Code Online (Sandbox Code Playgroud)
我的期望是一个(第六个)条具有不同的颜色,但是我得到了这个结果:
我究竟做错了什么?
发生这种情况是因为colorinpx.bar用于命名类别以使用色阶说明数据集的特征或维度。或者在您的情况下,而是一个颜色循环,因为您正在处理分类/离散情况。color_discrete_sequence然后用于指定要遵循的颜色顺序。使用此处的设置实现目标的一种方法是简单地定义具有唯一值的字符串变量,例如 like df['category'] [str(i) for i in df.index],然后使用:
fig=px.bar(df,x='Name',y='Value',
color = 'category',
color_discrete_sequence=color_discrete_sequence,
)
Run Code Online (Sandbox Code Playgroud)
如果df['category']是数值,color_discrete_sequence将被忽略,并应用默认的连续序列:
如果还有其他不清楚的地方,请随时告诉我。
import plotly.express as px
import pandas as pd
data = {'Name':['2020/01', '2020/02', '2020/03', '2020/04',
'2020/05', '2020/07', '2020/08'],
'Value':[34,56,66,78,99,55,22]}
df = pd.DataFrame(data)
df['category'] = [str(i) for i in df.index]
# df['category'] = df.index
color_discrete_sequence = ['#ec7c34']*len(df)
color_discrete_sequence[5] = '#609cd4'
fig=px.bar(df,x='Name',y='Value',
color = 'category',
color_discrete_sequence=color_discrete_sequence,
)
fig.show()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12836 次 |
| 最近记录: |