与ggplot2一起使用,根据lapply变量覆盖直方图和彩色geom_point以及名称图

时间:2018-05-16 19:10:32

标签: r ggplot2 lapply

我的问题分为两部分:

我。我想将--sslgeom_histogram重叠用于不同的geom_point变量

我的数据是:

aes

我的代码如下:

    df_test <- data.frame(structure(list(A= c(-0.80146, 0.190611, 0.028847, 
0.026058, -0.021505, 0.540703, 0.052167, 0.203469, 0.069915, 
0.148333, 0.005477, -0.001109, -0.116027, 0.473616, 0.120469, 
0.11245, 0.100045, 1.781763, -0.177578, 0.134783, -0.099096, 
-0.077076, 0.193608, 0.407867, -0.039539, 0.13453, 1.173945, 
-0.797383, -0.277112, -0.164893, -0.265595, 0.003697, 0.998122, 
-0.080394, 0.085291, -0.805778, -0.071481, -0.344804, -0.353637, 
-0.198817, 0.77241, 0.169778, 0.063251, 0.024213), B= c(0L, 
0L, 0L, 0L, -1L, 2L, 0L, 0L, -1L, 0L, 0L, 0L, 0L, 2L, -1L, 0L, 
0L, 2L, 0L, 0L, 0L, 0L, 1L, 1L, 0L, 0L, 1L, 0L, 0L, 0L, 0L, -1L, 
2L, 0L, 0L, -1L, 0L, 0L, 0L, 0L, 2L, -1L, 0L, 0L), C= c("GM1", 
"GM2", "GM3", "GM4", "GM5", "GM6", "GM7", "GM8", "GM9", "GM1", 
"GM2", "GM3", "GM4", "GM5", "GM6", "GM7", "GM8", "GM9", "GM1", 
"GM2", "GM3", "GM4", "GM5", "GM6", "GM7", "GM8", "GM9", "GM1", 
"GM2", "GM3", "GM4", "GM5", "GM6", "GM7", "GM8", "GM9", "GM1", 
"GM2", "GM3", "GM4", "GM5", "GM6", "GM7", "GM8")), .Names = c("A", 
"B", "C"), class = "data.frame", row.names = c(NA, 
44L)))

预期的输出图有点像这样(忽略顶部的红色箭头):

enter image description here

我无法:

我。为geom_point着色并根据变量library(ggplot2) regions = c('GM1', 'GM2', 'GM3', 'GM4', 'GM5', 'GM6', 'GM7', 'GM8', 'GM9') hist_plot <- function(df){ p = ggplot(df, aes(x=A)) + geom_histogram(fill='white', color='black') p = p + geom_point(aes(A,B)) + ggtitle(names(regions)) p } p = lapply(df_test, hist_plot)

为它们添加图例

II。根据lapply

中的区域命名每个图

有人可以提供建议吗?我尝试将颜色专门添加到geom_point但是出错了。谢谢!

1 个答案:

答案 0 :(得分:0)

如果我正确理解了这个问题,则不需要该功能和lapply。矢量regions也不是。您所需要的只是facet_wrap,如下所示 更重要的是,lapply(df, FUN)会将FUN应用于df的每个。这是因为数据帧是表格格式的列表。

现在代码。

p <- ggplot(df_test, aes(x = A)) + 
     geom_histogram(fill = 'white', color = 'black') +
     geom_point(aes(A, B, color = B)) + ggtitle(names(C)) + 
     facet_wrap( ~ C)
p

enter image description here