[英]R Plotly: Change legend symbol
How do I change the default legend symbols in R plotly?如何更改 R 中的默认图例符号? In my example below, I would like both symbols to be dots in the legend.在下面的示例中,我希望两个符号都是图例中的点。 The legend entry for "A" should be a blue circle. “A”的图例条目应该是一个蓝色圆圈。 (By default, Plotly uses the symbol of the first point for each category.) (默认情况下,Plotly 使用每个类别的第一个点的符号。)
library(plotly)
# generate example data
name = rep("A", 100)
name[1:100%%6 == 0] = "B"
data = data.frame(x = 1:100, y = sin(1:100),
name = name,
symbol = c(2, rep(1, 50), 2, 2,2, 2, 2, 2, rep(1, 43)))
plot_ly(data)%>%
add_markers(x = ~x, y = ~y, symbol = ~symbol,
symbols = c(27, 4),
mode = 'markers', split = ~name)
By mapping symbol and color argument to a factor variable you can create one trace per symbol and name.通过将符号和颜色参数映射到因子变量,您可以为每个符号和名称创建一个轨迹。 The following code may solve your problem:以下代码可能会解决您的问题:
col3 <- colorRamp(c("red", "blue"))
p = plot_ly(data,x = ~x, y = ~y)
add_markers(p, symbol = ~factor(symbol),
color = ~factor(name),
colors = col3, symbols = c(27,4))
Check this link for more details on scatter plot traces https://plotly-book.cpsievert.me/scatter-traces.html检查此链接以获取有关散点图跟踪的更多详细信息https://plotly-book.cpsievert.me/scatter-traces.html
Ah, plotly
has picked up the first entry of the symbol
column to use in its legend.啊, plotly
已经选择了symbol
列的第一个条目以在其图例中使用。
> head(data[data$name == 'A', ])
x y name symbol
1 1 0.8414710 A 2 # The first value is 2
2 2 0.9092974 A 1
3 3 0.1411200 A 1
4 4 -0.7568025 A 1
5 5 -0.9589243 A 1
7 7 0.6569866 A 1
Whereas, in case of 'B', -而在“B”的情况下,-
> head(data[data$name == 'B', ])
x y name symbol
6 6 -0.2794155 B 1 # The first value is 1
12 12 -0.5365729 B 1
18 18 -0.7509872 B 1
24 24 -0.9055784 B 1
30 30 -0.9880316 B 1
36 36 -0.9917789 B 1
If you sort your data by name
and symbol
, then the legend should be consistent.如果您按name
和symbol
对数据进行排序,那么图例应该是一致的。
library(plotly)
# generate example data
name = rep("A", 100)
name[1:100%%6 == 0] = "B"
data = data.frame(x = 1:100, y = sin(1:100),
name = name,
symbol = c(2, rep(1, 50), 2, 2,2, 2, 2, 2, rep(1, 43)))
data <- data[with(data, order(symbol, name)), ]
plot_ly(data)%>%
add_markers(x = ~x, y = ~y, symbol = ~symbol, symbols = c(27, 4),
mode = 'markers', split = ~name)
We can try symbols = I(c('27', '4'))
for specifying symbols if we use a 2 level categorical variable for the symbols.如果我们对符号使用 2 级分类变量,我们可以尝试symbols = I(c('27', '4'))
来指定符号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.