gpt4 book ai didi

r - 如何控制箱线图点的颜色?

转载 作者:行者123 更新时间:2023-12-05 03:10:24 24 4
gpt4 key购买 nike

我想使用 native 绘图功能重现此 ggplot 图

ggplot(mtcars, aes(x="mpg", y=mpg))+
geom_boxplot()+geom_jitter(aes(color = mpg),width = 0.3,size=4)+
scale_color_gradient(low="blue", high="yellow", guide = 'none')
ggplotly()

我正在尝试做这样的事情

    plot_ly(data=mtcars, y = ~mpg, 
type = "box", boxpoints = "all", jitter = 0.3,
marker=list(color=~mpg, size=10),pointpos = 0)

但是我找不到控制点颜色的方法(color=~mpg什么都不做)

我需要使用原生 plotly 而不是使用上面提到的“plotlyfied”ggplot 来实现它的原因是我需要与在原生 plotly 中实现的其他绘图保持样式一致。

最佳答案

这有点 hack,但它有效:

  1. 使用单独的轨迹绘制箱线图(不带点)
  2. 添加第二条散点类型的轨迹来绘制点
  3. 不幸的是,散点图不接受抖 Action 为参数
  4. 这意味着我们需要在 x 轴上使用连续刻度,并使用 rnorm
  5. 添加抖动
  6. 我们真的不希望 x 轴看起来像一个连续的数字刻度,所以我们手动设置刻度标签看起来像类别

像这样:

plot_ly(data=mtcars) %>%
add_trace(y = ~mpg, x=1, type = "box", boxpoints = "none") %>%
add_trace(type="scatter", mode="markers",
y=~mpg, x=rnorm(nrow(mtcars),1,0.05), marker=list(color = ~mpg, size=10))%>%
layout(xaxis = list(tickmode="array", tickvals=c(1), ticktext=c("mtcars") ))

enter image description here

您可以扩展此方法以拥有多个这样的类别

plot_ly(data=mtcars) %>%
add_trace(y = ~mpg, x=~gear, type = "box", boxpoints = "none") %>%
add_trace(type="scatter", mode="markers", y=~mpg,
x = ~gear+rnorm(nrow(mtcars),0,0.1),
marker=list(color = ~mpg, size=10))%>%
layout(xaxis = list(tickmode="array", tickvals=c(3,4,5), ticktext=c("3","4","5") ))

enter image description here

要控制标记颜色,您可以使用 colorscale 参数以及 autocolorscale = FALSE

The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required.

例如,

cs = list(list(0, rgb(0,0,1)), list(1, rgb(1,1,0)))
plot_ly(data=mtcars) %>%
add_trace(y = ~mpg, x=1, type = "box", boxpoints = "none") %>%
add_trace(type="scatter", mode="markers",
y=~mpg, x=rnorm(nrow(mtcars),1,0.05),
marker=list(color = ~mpg, autocolorscale=F,
colorscale = cs, size = 10)) %>%
layout(xaxis = list(tickmode="array", tickvals=c(1), ticktext=c("mtcars") ))

enter image description here

关于r - 如何控制箱线图点的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40223848/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com