[英]Plotly barchart (graph object GO) different marker pattern shape depending on the specific column value
[由@Rob Raymond 第二个答案解决]
我一直在努力定义模式形状源(特定的列值)。
我想根据列名“大小”定义图案形状(“//”、“.”等)。
最小可重现示例:
import plotly.graph_objects as go
import pandas as pd
animals=['giraffes', 'orangutans', 'monkeys', 'rats']
size=['big', 'medium', 'medium', 'small']
number=[20, 14, 23, 5]
columns = ['animal','size','number','test']
df = pd.DataFrame({'animals':animals, 'size':size,'number':number})
fig = go.Figure([go.Bar( x=df['animals'].values.tolist(), y=df['number'].values.tolist())])
fig.update_traces(marker_pattern_shape=['.', '\\','+','/'])
fig.show()
动物 | 尺寸 | 数字 | |
---|---|---|---|
1 | 长颈鹿 | 大 | 20 |
2 | 猩猩 | 中等的 | 14 |
3 | 猴子 | 中等的 | 23 |
4 | 老鼠 | 小的 | 5 |
我一直在尝试以下几行:
fig.update_traces(marker_pattern_shape=['.', '\\\\','+','/'], marker_pattern = {'shape':['+', '\\\\']})
go.Bar(..., marker = {'pattern':'.'}, ...)
附注。 我被迫使用 plotly GO 而不是 ploty express。 很长的故事。
它适用于第一个解决方案,但不适用于我创建的科学怪人。 下面更复杂的最小可重现示例:
import plotly.graph_objects as go
import pandas as pd
animals=['giraffes', 'orangutans', 'monkeys', 'rats', "mice"]
size=['big', 'medium', 'medium', 'small', "small"]
number=[20, 14, 23, 5, 4]
animalId=[1,2,3,4,5]
colorPlotly = ['lightslategrey','red','black', 'saddlebrown','grey']
df = pd.DataFrame({'animals':animals, 'size':size,'number':number,'animalId':animalId, 'colorPlotly':colorPlotly})
fig = go.Figure()
for id in animalId:
fig.add_trace(go.Bar(
x=df[df['animalId']==id]['animals'],
y=df[df['animalId']==id]['number'],
name = id,
marker_color=df[df['animalId']==id]['colorPlotly']))
fig.update_traces(marker_pattern_shape=df["size"].map({'big':".", 'medium':"\\", 'medium':"+", 'small':"/"}))
fig.show()
动物 | 尺寸 | 数字 | colorPlotly | 动物ID | |
---|---|---|---|---|---|
1 | 长颈鹿 | 大 | 20 | 浅灰色 | 1 |
2 | 猩猩 | 中等的 | 14 | 红色的 | 2 |
3 | 猴子 | 中等的 | 23 | 黑色的 | 3 |
4 | 老鼠 | 小的 | 4 | 马鞍褐色 | 4 |
5 | 老鼠 | 小的 | 5 | 灰色的 | 5 |
import plotly.graph_objects as go
import pandas as pd
animals=['giraffes', 'orangutans', 'monkeys', 'rats', "mice"]
size=['big', 'medium', 'medium', 'small', "small"]
number=[20, 14, 23, 5, 4]
df = pd.DataFrame({'animals':animals, 'size':size,'number':number})
fig = go.Figure([go.Bar( x=df['animals'], y=df['number'])])
fig.update_traces(marker_pattern_shape=df["size"].map({'big':".", 'medium':"\\", 'medium':"+", 'small':"/"}))
fig.show()
animal_map = {k:v for k, v in zip(animals, np.tile(['/', '\\', 'x', '-', '|', '+', '.'], 3)[:len(animals)])}
fig = go.Figure()
for id in animalId:
fig.add_trace(
go.Bar(
x=df[df["animalId"] == id]["animals"],
y=df[df["animalId"] == id]["number"],
name=id,
marker_color=df[df["animalId"] == id]["colorPlotly"],
marker_pattern_shape=df.loc[df["animalId"] == id, "animals"].map(animal_map)
)
)
fig.show()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.