R 用多条线高亮显示ggplot中的一条线
我想更改ggplot中一行的R 用多条线高亮显示ggplot中的一条线,r,ggplot2,highlight,R,Ggplot2,Highlight,我想更改ggplot中一行的大小,线型,颜色等。 以下是一个最小的可复制示例: library(tidyverse) # Data in wide format df_wide <- data.frame( Horizons = seq(1,10,1), Country1 = c(2.5, 2.3, 2.2, 2.2, 2.1, 2.0, 1.7, 1.8, 1.7, 1.6), Country2 = c(3.5, 3.3, 3.2, 3.2, 3.
大小
,线型
,颜色
等。
以下是一个最小的可复制示例:
library(tidyverse)
# Data in wide format
df_wide <- data.frame(
Horizons = seq(1,10,1),
Country1 = c(2.5, 2.3, 2.2, 2.2, 2.1, 2.0, 1.7, 1.8, 1.7, 1.6),
Country2 = c(3.5, 3.3, 3.2, 3.2, 3.1, 3.0, 3.7, 3.8, 3.7, 3.6),
Country3 = c(1.5, 1.3, 1.2, 1.2, 1.1, 1.0, 0.7, 0.8, 0.7, 0.6)
)
# Convert to long format
df_long <- df_wide %>%
gather(key = "variable", value = "value", -Horizons)
# Plot the lines
plotstov <- ggplot(df_long, aes(x = Horizons, y = value)) +
geom_line(aes(colour = variable, group = variable))+
theme_bw()
库(tidyverse)
#宽格式数据
df_wide并非每一行,但您只能单独绘制“Country1”:
library(ggplot2)
ggplot(subset(df_long, variable != 'Country1'), aes(x = Horizons, y = value)) +
geom_line(aes(colour = variable, group = variable)) +
geom_line(data = subset(df_long, variable == 'Country1'),
size = 3, linetype = 'dashed', color = 'blue') +
theme_bw()
实现这一点的一种方法是为颜色
,大小
。。然后,您可以在scale\u xxxx\u manual
中使用它来设置您喜欢的值
库(tidyverse)
#宽格式数据
下面是这个问题的另一个答案。
它使用了一个简单的技巧,通过将高亮显示的变量与目标值进行比较来告诉它。这种二分法将其分为逻辑值FALSE/TRUE
variable == "Country1"
情节图例现在需要更多的注意,以便标题和文本正确
g <- ggplot(df_long, aes(x = Horizons, y = value)) +
geom_line(aes(colour = variable == "Country1", size = variable == "Country1", group = variable)) +
scale_color_manual(name = "variable", labels = c("Other", "Country1"), values = c("grey50", "red")) +
scale_size_manual(name = "variable", labels = c("Other", "Country1"), values = c(0.5, 2)) +
theme_bw()
g
g您可以应用相同的逻辑