【发布时间】:2021-02-25 19:17:51
【问题描述】:
我的图例中出现了奇怪的元素,而我通过悬停显示的工具提示文本具有随机的颜色和形状线条。
样本数据:
> dput(sample_n(Plot, 20))
structure(list(Strain = c(0.0099576, 0.00550752, 0.0255111, 0.00341572,
0.000323357, 0.0036487, 0.0265925, 0.00438567, 0.00437111, 0.0214385,
0.00957133, 0.00144209, 0.0237199, 0.00290038, 0.00786047, 0.0114374,
0.000582628, 0.00961509, 0.0110853, 0.00333173), Stress = c(74.4928907635218,
65.7454752463861, 86.6080612547546, 63.8155559103337, 15.8799350673083,
63.7937705218785, 76.1766851002328, 64.1491550648465, 64.0561929873925,
84.7109031517226, 64.7832595395012, 46.2442265654563, 85.8590430135155,
63.3618876683043, 71.5077936431304, 76.5758067207865, 26.3220708755176,
74.1047449875333, 76.1658755563428, 63.6570713668388), Instrumentation = structure(c(1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L), .Label = c("DIC", "Gauge"), class = "factor"), Bar = structure(c(1L,
1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L), .Label = c("Spliced", "Unspliced"), class = "factor")), row.names = c(NA,
-20L), class = "data.frame")
我尝试通过子集来绘制数据,以便可以组合 geom_point 和 geom_line。然而,这似乎使传说变得复杂。 scale_color_manual 中指定的颜色仅适用于 geom_line,因此我必须为 geom_point 中的点定义颜色,现在我在 tooptip 的文本中获得了额外的输入。
plot <- ggplot(data = subset(Plot, Instrumentation == "DIC"), aes(x = Strain, y = Stress,
colour = Instrumentation, linetype = Bar)) +
geom_line(size = 0.8) + theme_classic() +
geom_point(data = subset(Plot, Instrumentation == "Gauge"),
aes(colour = Instrumentation, shape = Bar), colour = "blue", size = 2) +
labs(x = "Strain (in/in)", y = "Stress (ksi)") + scale_color_manual(values = c("DIC"="red", "LVDT"="blue")) +
theme_classic() + theme(axis.text = element_text(color = "black", size = 16),
axis.line = element_line(color = "black", size = 0.2), axis.ticks.y = element_line(color = "black", size = 0.2),
axis.title.y = element_text(color = "black", size = 20, margin = margin(0,40,0,0)),
axis.title.x = element_text(color = "black", size = 20, margin = margin(35,0,0,0)),
legend.title = element_blank(), legend.text = element_text(color = "black", size = 16))
ggplotly(
p = ggplot2::last_plot(),
width = NULL,
height = NULL,
tooltip = c("Strain","Stress","Instrumentation","Bar"),
dynamicTicks = FALSE,
layerData = 1,
originalData = TRUE,) %>%
layout(yaxis = list(title = list(text = "Stress (ksi)", standoff = 30L)),
xaxis = list(title = list(text = "Strain (in/in)",standoff = 30L)),
legend = list(orientation = "v", x = 0.7, y = 0.13))
屏幕截图显示了当前代码下的绘图效果。有没有更好的方法来分配颜色而不弄乱图例?
【问题讨论】: