如何修改Plotly Treemap(树形图)的颜色?
修改Plotly Treemap颜色的方法
要调整树形图的颜色,你只需要在plot_ly()函数里添加或修改相关参数即可,下面是几种实用的修改方式:
1. 自定义固定颜色数组
直接给每个类别指定固定颜色,在marker参数中传入colors向量,向量长度要和你的数据行数一致(这里是13个):
plot_ly( dtd7 %>% mutate(n = as.numeric(as.character(n))), labels = ~topic, parents = NA, values = ~n, type = 'treemap', hovertemplate = "Category: %{label}<br>Percent: %{value}%<extra></extra>", # 添加颜色配置 marker = list( colors = c("#FF6B6B", "#4ECDC4", "#45B7D1", "#96CEB4", "#FFEAA7", "#DDA0DD", "#98D8C8", "#F7DC6F", "#BB8FCE", "#85C1E9", "#F8C471", "#82E0AA", "#F1948A") ) )
2. 根据数值自动渐变上色
如果想让颜色随n值的大小变化,用color参数绑定数值列,再通过colorscale选择配色方案(Plotly内置了很多配色,比如"Viridis"、"Blues"、"Reds"等):
plot_ly( dtd7 %>% mutate(n = as.numeric(as.character(n))), labels = ~topic, parents = NA, values = ~n, type = 'treemap', hovertemplate = "Category: %{label}<br>Percent: %{value}%<extra></extra>", # 根据n值自动上色 color = ~n, colorscale = "Viridis", # 可选:显示颜色条 colorbar = list(title = "Percent") )
3. 手动指定每个类别的颜色(关联数据列)
先在数据框里新增一列存储对应类别的颜色,再绑定到marker的colors参数,方便精准控制:
# 先给数据框添加颜色列 dtd7_colored <- dtd7 %>% mutate( n = as.numeric(as.character(n)), # 给每个topic指定对应颜色 category_color = case_when( topic == "Alcoholic Beverages" ~ "#FF5733", topic == "Apparel" ~ "#33FF57", topic == "Used Cars and Trucks" ~ "#3357FF", # 其他类别依次补充 TRUE ~ "#CCCCCC" # 默认颜色 ) ) # 绘制树形图 plot_ly( dtd7_colored, labels = ~topic, parents = NA, values = ~n, type = 'treemap', hovertemplate = "Category: %{label}<br>Percent: %{value}%<extra></extra>", marker = list(colors = ~category_color) )
内容的提问来源于stack exchange,提问作者Data and AI Nerd
相关产品推荐
相关产品推荐

