为ggplot2生成的多个图表添加标题和格式化Y轴标签

时间:2017-04-11 12:43:52

标签: r ggplot2 scatter-plot

我有一个使用ggplot2生成10个散点图的多重图。我用来创建情节的代码已从这里解除R cookbook.我的问题是我想为每个散点图添加不同的标题,例如,情节1标题可以标题为“情节1”,而情节2可以标题为“图2”,依此类推。我还想将所有图表中的标签从当前标签“Y”更改为“购买”。

1 个答案:

答案 0 :(得分:1)

只需按照引用的代码单独创建每个图和标题。然后使用gridExtra包安排。 ggtitle标题,ylab函数可用于y标签。

library(ggplot2)

# This example uses the ChickWeight dataset, which comes with ggplot2
# First plot
p1 <- ggplot(ChickWeight, aes(x=Time, y=weight, colour=Diet, group=Chick)) +
    geom_line() +
    ggtitle("Growth curve for individual chicks")

# Second plot
p2 <- ggplot(ChickWeight, aes(x=Time, y=weight, colour=Diet)) +
    geom_point(alpha=.3) +
    geom_smooth(alpha=.2, size=1) +
    ggtitle("Fitted growth curve per diet")

 # Third plot
p3 <- ggplot(subset(ChickWeight, Time==21), aes(x=weight, colour=Diet)) +
    geom_density() +
    ggtitle("Final weight, by diet")

# Fourth plot
p4 <- ggplot(subset(ChickWeight, Time==21), aes(x=weight, fill=Diet)) +
    geom_histogram(colour="black", binwidth=50) +
    facet_grid(Diet ~ .) +
    ggtitle("Final weight, by diet") +
    theme(legend.position="none")        # No legend (redundant in this graph)    

require(gridExtra)
grid.arrange(p1, p2, p3, p4, nrow = 2)