首页 > 解决方案 > 使用“plot_ly”的线条和标记的自定义颜色问题

问题描述

假设我想为线条+标记绘图使用自定义颜色。使用colorscolor参数非常简单,plot_ly()但是一旦我想自己修改标记(使用marker参数),我就会遇到困难并且在网上找不到解决这个特定问题的帮助。有人可以告诉我我做错了什么吗?

# Underlying data
tmp <- mpg %>%
  group_by(class,manufacturer) %>%
  summarise(models=n())

# Works as expected
tmp %>% 
  plot_ly(x=~manufacturer, 
          y=~models, 
          group=~class,
          type="scatter",
          color=~class, 
          colors = scales::hue_pal()(length(n_distinct(tmp$class))), #ggplot colors
          mode="lines+markers")

# Issue with markers > idea behind is to have a white center and a marker line with the same color as the line itself
tmp %>% 
  plot_ly(x=~manufacturer, 
          y=~models, 
          group=~class,
          type="scatter",
          color=~class, 
          colors = scales::hue_pal()(n_distinct(tmp$class)),
          marker = list(color = 'rgba(255, 255, 255, 1)',
                        line = list(color = scales::hue_pal()(n_distinct(tmp$class)))),
          mode="lines+markers")

标签: rplotlyr-plotly

解决方案


这可能看起来有点奇怪,但在您的情况下,非常简单的解决方案是放弃:

line = list(color = scales::hue_pal()(n_distinct(tmp$class))))

并且仅包括:

line = list(width = 3)

这是你现在的情节:

在此处输入图像描述

完整代码:

# Underlying data
tmp <- mpg %>%
  group_by(class,manufacturer) %>%
  summarise(models=n())


# Issue with markers > idea behind is to have a white center and a marker line with the same color as the line itself
tmp %>% 
  plot_ly(x=~manufacturer, 
          y=~models, 
          group=~class,
          type="scatter",
          color=~class, 
          colors = scales::hue_pal()(n_distinct(tmp$class)),
          marker = list(color = 'rgba(255, 255, 255, 1)',
                        line = list(width = 3)),
          mode="lines+markers")
tmp

推荐阅读