[英]ggplot multiple stacked bar charts for large x-axis dataset
I have the following code - the dataset results in 78 stacked bars. 我有以下代码-数据集产生了78个堆积的条形图。 Does ggplot have a way to break on, say 8 bars per graph? ggplot是否有办法突破,比如说每张图8条? I could break up the dataframe via loop but that seems pretty inefficient. 我可以通过循环分解数据帧,但这似乎效率很低。
TTM <- read.csv("c:/temp/out.csv", header=TRUE)
library(ggplot2)
ggplot(data = TTM, aes(x = MTF, y = FTE, fill = Job)) +
geom_bar(stat="identity")
Since you didn't provide any sample data, I'll use a built in dataset mtcars
. 由于您未提供任何示例数据,因此我将使用内置数据集mtcars
。 Expanding on my comment above you could create a new group variable that has the number of groups you want. 在上面的评论中,您可以创建一个新的组变量,该变量具有所需的组数。 Using this you can do 1 of 3 things: (1) Facet_wrap
, (2) grid.arrange
, or (3) new pages 使用此方法,您可以执行3件事情中的1件:(1) Facet_wrap
,(2) grid.arrange
或(3)新页面
Data setup: 数据设置:
group.len <- 8
map <- data.frame(hp = unique(mtcars$hp),
new_group = rep(1:ceiling(length(unique(mtcars$hp))/group.len), each = group.len,
length.out = length(unique(mtcars$hp))))
df <- merge(mtcars, map)
Facet wrap: 小面环绕:
ggplot(data = df, aes(x = cyl, y = mpg, fill = as.factor(hp))) +
geom_bar(stat="identity") + facet_wrap(~new_group)
Grid.arrange: Grid.arrange:
I use the same exact approach as in this post place a legend for each facet_wrap grid in ggplot2 . 我使用与本博文相同的方法, 为ggplot2中的每个facet_wrap网格放置一个图例 。 The original was about getting different legends for each facet, but I think it's also very applicable to your problem: 最初是关于每个方面获得不同的图例,但我认为这也非常适用于您的问题:
library(gridExtra)
out <- by(data = df, INDICES = df$new_group, FUN = function(m) {
m <- droplevels(m)
m <- ggplot(m, aes(as.factor(cyl), mpg, fill = as.factor(hp))) +
geom_bar(stat="identity")
})
do.call(grid.arrange, out)
Note this uses the out
object from grid.arrange . 请注意,这使用了grid.arrange中的out
对象。 This will put each plot on a new page (instead of all on one page like in grid.arrange
. 这会将每个图放在新页面上(而不是像在grid.arrange
那样将所有图放在一个页面上)。
lapply(out, function(x) {x})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.