Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/jsp/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 在密度图上添加标签和图例_R_Ggplot2_Density Plot - Fatal编程技术网

R 在密度图上添加标签和图例

R 在密度图上添加标签和图例,r,ggplot2,density-plot,R,Ggplot2,Density Plot,我试图在同一个图上画两个密度图。我尝试了以下代码 car Bus 48.1 17.8 47.2 21.2 69.9 27 72.7 9.1 73.8 23.9 67.7 4.9 61.1 12.3 61.6 0.4 4.7 20.9 5.5 19.8 5.9 14.3 16.3 library(ggplot2) m <

我试图在同一个图上画两个密度图。我尝试了以下代码

car     Bus
48.1    17.8
47.2    21.2
69.9    27
72.7    9.1
73.8    23.9
67.7    4.9
61.1    12.3
61.6    0.4
        4.7
        20.9
        5.5
        19.8
         5.9
        14.3
        16.3


 library(ggplot2)
m <-ggplot()+geom_density(aes(data$column1),color='red')+geom_density(aes(data$column2), color='blue') 
car-Bus
48.1    17.8
47.2    21.2
六十九点九二七
72.7    9.1
73.8    23.9
67.7    4.9
61.1    12.3
61.6    0.4
4.7
20.9
5.5
19.8
5.9
14.3
16.3
图书馆(GG2)

m您应该将两个变量叠加在一起,并用一个因子变量说明它是哪一列。然后,您可以添加标签并选择如下颜色:

data <- read.table(text = "
column1 column2
48.1    17.8
47.2    21.2
69.9    27
72.7    9.1
73.8    23.9
67.7    4.9
61.1    12.3
61.6    0.4
NA        4.7
NA        20.9
NA        5.5
NA        19.8
NA         5.9
NA        14.3
NA        16.3", header = TRUE)
plot.data <- data.frame(x      = c(data$column1, data$column2),
                        column = paste("column", rep(c(1:2), each = nrow(df))))
library(ggplot2)
m <-ggplot(plot.data, aes(x = x, fill = column)) + geom_density(alpha = 0.5) +
  xlab("My x label") + ylab("My y label") +
  scale_fill_manual(name = "My legend title", values = c("red", "blue"))

data您应该将两个变量堆叠在一起,并用一个因子变量说明它是哪一列。然后,您可以添加标签并选择如下颜色:

data <- read.table(text = "
column1 column2
48.1    17.8
47.2    21.2
69.9    27
72.7    9.1
73.8    23.9
67.7    4.9
61.1    12.3
61.6    0.4
NA        4.7
NA        20.9
NA        5.5
NA        19.8
NA         5.9
NA        14.3
NA        16.3", header = TRUE)
plot.data <- data.frame(x      = c(data$column1, data$column2),
                        column = paste("column", rep(c(1:2), each = nrow(df))))
library(ggplot2)
m <-ggplot(plot.data, aes(x = x, fill = column)) + geom_density(alpha = 0.5) +
  xlab("My x label") + ylab("My y label") +
  scale_fill_manual(name = "My legend title", values = c("red", "blue"))

数据文档对此主题有何说明?我没有看到任何数据。请至少发布一些您的数据。关于这个主题的文档说明了什么?我没有看到任何数据。请至少发布一些数据。如何将图例添加为car和bus而不是column1和column2?您可以使用
column=c(rep(“car”),nrow(data)),rep(“bus”,nrow(data)))
在内部而不是在其中添加图例。如何将图例添加为car和bus而不是column1和column2?您可以使用
column=c(rep(“car”),nrow(data)),rep(“总线”,nrow(data)))
内部,而不是其中的内容