我正在尝试绘制在 ggplot 中分组变量的多个数据集,但我遇到了一些问题。好的,所以我有两个数据集:
df.1 <- data.frame(
name = c( "a", "b", "c", "d" ),
x = c( 3, 2, 1, 2 ),
y = c( 4, 3, 4, 3 ),
z = c( 8, 9, 6, 7 ) )
df.2 <- data.frame(
name = c( "o", "p", "q", "r" ),
x = c( 8, 7, 6, 9 ),
y = c( 4, 1, 4, 3 ),
z = c( 1, 2, 2, 2 ) )
然后我将它们每个都融化并按名称分组
df.1.melted <- melt( df.1, id.vars = "name" )
df.2.melted <- melt( df.2, id.vars = "name" )
现在,我想要一个 x 轴为 x
的图。 , y
,和z
分组,y 轴是值,每个样本通过 name
链接已经给了它。我可以对其中一个数据集执行此操作(我最终想要一个对数刻度,因此将其包括在内):
ggplot( df.1.melted, aes( x = variable,
y = value,
group = df.1.melted$name,
col = df.1.melted$name ) ) +
scale_y_continuous( trans = log_trans(), limits = c( 1, 10 ),
breaks = c( 1, 10 ) ) +
labs( x = "", y = "value" ) +
geom_point( size = 4 ) +
geom_line( size = 1 )
然后我可以通过以下方式添加第二个数据集:
ggplot( df.1.melted, aes( x = variable,
y = value,
group = df.1.melted$name,
col = df.1.melted$name ) ) +
scale_y_continuous( trans = log_trans(), limits = c( 1, 10 ),
breaks = c( 1, 10 ) ) +
labs( x = "", y = "value" ) +
geom_point( size = 4 ) +
geom_line( size = 1 ) +
geom_point( data = df.2.melted, aes( x = df.2.melted$variable,
y = df.2.melted$value,
group = df.2.melted$name,
col = df.2.melted$name ),
size = 4 ) +
geom_line( data = df.2.melted, aes( x = df.2.melted$variable,
y = df.2.melted$value,
group = df.2.melted$name,
col = df.2.melted$name ),
size = 1 )
这是我所追求的主题,但我遇到了一些问题:
1) 使用 aes( group = ...)
时如何覆盖默认配色方案部分?我希望在数据框中具有预定义的颜色,或者能够在 geom_point()
中定义它们。颜色应该是我正在使用的数据框所特有的,所以 df.1.melted
是 darkgreen
和df.2.melted
是 orange
或类似的东西。我还没有找到如何在不使用 group =
的情况下绘制这些图像在 aes()
打电话,所以目前找不到解决方法。
该解决方案看起来是可行的,如 ggplot
所示此处答案中的示例:
R plotly - Plotting grouped lines
但是,我对 dplyr
还不够熟悉弄清楚这个情节的发生是怎么回事。
感谢您的建议
最佳答案
你可以试试这个
library(ggplot2)
library(dplyr)
df_melted <- bind_rows(df.1.melted, df.2.melted)
df_melted %>%
mutate(df = rep(c('df.1', 'df.2'), each = nrow(df_melted) / 2)) %>%
ggplot(aes(x = variable,
y = value,
col = df)) +
geom_line(aes(group = name)) +
geom_point() +
scale_y_log10(limits = c( 1, 10),
breaks = c(1, 10)) +
scale_color_manual(values = c('df.1' = "forestgreen",
'df.2' = "orange"))
其想法是创建一个数据框 df_melted
,并添加列 df
来指示观测值来自哪个数据框。然后您可以将变量 df 映射到颜色美感。正如评论中所建议的,您可以使用 scale_colour_manual
更改默认颜色。
关于r - 在 ggplot 中绘制多个分组变量数据集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48409592/