gpt4 book ai didi

r - 以 plotly 方式操作 R 中的图例文本

转载 作者:行者123 更新时间:2023-12-04 08:21:42 25 4
gpt4 key购买 nike

我有一个 data.frame我想使用 R 散点图的 plotly我想用两个因素来着色和塑造形状。

这是我的数据:

set.seed(1)
df <- data.frame(x=rnorm(12),y=rnorm(12),
group=c(rep(1,3),rep(2,3),rep(3,3),rep(4,3)),
treatment=c(rep("A",6),rep("B",6)),
stringsAsFactors=F)

df$group <- factor(df$group,levels=1:4)
df$treatment <- factor(df$treatment,levels=c("A","B"))

这是我试图绘制的方式:
require(plotly)

plot_ly(marker=list(size=10),type='scatter',mode="markers",x=~df$x,y=~df$y,color=~df$group,symbol=~df$treatment) %>%
add_annotations(text="group,treatment",xref="paper",yref="paper",x=1.02, xanchor="left",y=1.02,yanchor="top",legendtitle=TRUE,showarrow=FALSE) %>%
layout(xaxis=list(title="x"),yaxis=list(title="y"))

这给了我:
enter image description here

是否可以获取 group 的文本?和 treatment在图例中用逗号分隔而不是像现在这样的新行?

这意味着,而不是:

1

一种

2

一种

3



4



我会有:

1,A

2,A

3、乙

4、乙

最佳答案

听起来微不足道,但这是 Plotly 的情况之一决定什么对你有好处。

图例标签由 color 的类别组成。和 symbol这些都在一个命令中传递。为了控制输出,让我们分别添加每个跟踪。

for (grou in groups) {
for (treat in treatments) {
trace_data <- subset(df, group == grou & treatment == treat)
if (nrow(trace_data) > 0) {
p <- add_trace(p,
x = trace_data$x,
y = trace_data$y,
marker = list(size = 10,
color = group,
symbol = as.integer(charToRaw(treat)) - 65),
type = 'scatter',
mode = "markers",
name = paste(grou, treat, sep = ",")
)
}
}
}

我们通过 color (并非绝对必要)通过 markersymbol也通过 marker (两者都可以在 add_trace 命令中传递,但 Plotly 再次决定如何处理它)。

图例标签通过 name 传递.

注意:您需要显式转换您的处理方式,因为符号需要命名符号或数字(除非您的处理方式命名为 diamondcircle )

enter image description here

完整代码
library(utils)
library(plotly)

set.seed(1)
df <- data.frame(x = rnorm(12),
y = rnorm(12),
group = c(rep(1, 3),
rep(2, 3),
rep(3, 3),
rep(4, 3)
),
treatment=c(rep("A", 6),
rep("B", 6)
),
stringsAsFactors = FALSE
)

groups <- unique(df$group)
treatments <- unique(df$treatment)

p <- plot_ly()
for (grou in groups) {
for (treat in treatments) {
trace_data <- subset(df, group == grou & treatment == treat)
if (nrow(trace_data) > 0) {
p <- add_trace(p,
x = trace_data$x,
y = trace_data$y,
marker = list(size = 10,
color = group,
symbol = as.integer(charToRaw(treat)) - 65),
type = 'scatter',
mode = "markers",
name = paste(grou, treat, sep = ",")
)
}
}
}
p <- add_annotations(p,
text = "group,treatment",
xref = "paper",
yref = "paper",
x = 0.96,
xanchor = "left",
y = 1.03,
yanchor = "top",
legendtitle = TRUE,
showarrow = FALSE) %>%
layout(xaxis = list(title = "x"),
yaxis = list(title = "y"))

p

关于r - 以 plotly 方式操作 R 中的图例文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43432881/

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