我想制作密度图来比较数据分布模式。所以我按照下面的命令做了。
graph<-ggplot (data=data1, aes (x=grain_weight) + geom_density() + geom_density (data=data2, aes (x=grain_weight) + geom_density (data=data3, aes (x=grain_weight) + labs(title="Distribution") + labs (y="Frequency") + labs(x="Grain weight")
1)现在,我想区分每个图表,在图例上添加标签或制作颜色。我该怎么办?
2)我想将X轴从0调整到150.我该怎么做?
3)我想将背景颜色设为白色。你能帮我怎么做吗?
答案 0 :(得分:0)
也许这就足够了?
graph<-ggplot () +
geom_density(data=data1, aes (x=grain_weight), col = 'blue') +
geom_density (data=data2, aes (x=grain_weight), col = 'red') +
geom_density (data=data3, aes (x=grain_weight), col = 'yellow') +
labs(title="Distribution") +
labs (y="Frequency") +
labs(x="Grain weight") +
xlim(c(0,150)) +
theme_classic()
答案 1 :(得分:0)
您可以查看ggplot2
文档和示例,也可以查看dplyr
包。对我而言,简单的方法是改变你的data.frames
添加一个名为dataset的新col。在这个例子中,我将使用dplyr::bind_rows()
函数将所有data.frames合并为一个,并为每个data.frame添加一个id为的列。
library(dplyr)
library(ggplot2)
#some dummy data for this example
data1 = data.frame(x = rnorm(100, 5, 1))
data2 = data.frame(x = rnorm(100, 3, 4))
data3 = data.frame(x = rnorm(100, 2, 3))
# Combine the data.frames into one
all.data <- bind_rows("my data1" = data1, #you can use the name what you want to replace "my data.."
"my data2" = data2,
"my data3" = data3,
.id = "Dataset") # the name to identify each data.frame
ggplot(data = all.data,
mapping = aes(x = x,
color = Dataset)) + # the `color` argument inside aes() is
# to map each group of data
geom_density() #whatever geom you want to plot
为了更有效地使用ggplot2,我建议您阅读function reference of ggplot2,ggplot2: Elegant Graphics for Data Analysis (Use R!)和The Hitchhiker's Guide to Ggplot2