有没有办法在barplot或ggplot的同一图表上使用条形图和堆积条形图?

时间:2015-05-08 15:00:06

标签: r ggplot2 bar-chart rstudio

我想要将两个数据叠加到同一个图上。我已经查看了几篇ggplot文章,我认为在ggplot中它是不可能的。所以我一直在使用barplot。我有5层,我按层排列总计美元作为实心栏。

然后我有另一条数据代表两个不同类型的工人在这些等级中的任务数量。我把它作为堆积条形图。但是我想在同一个图表上显示它们,总金额为一个条形,然后是旁边相应的堆叠条形图。

以下是情节: Stacked Barchart of Total Tasks by Worker Type

Barchart of Total Dollars in each tier

第一张图的数据如下所示(它是一张表):

for(;;)

第二张图的数据如下所示(这是一个数据集):

        1     2     3     4     5
  0     9   340    97   812  4271
  1     1   417   156  3163 11314

我想把图表放在彼此的顶部但是条形图保持重叠,我希望它们能够一层一层地出现。

我目前的代码。

    Tier    variable    value
1   1   Opp_Amt 16200.00
2   2   Opp_Amt 116067.50
3   3   Opp_Amt 35284.12
4   4   Opp_Amt 278107.10
5   5   Opp_Amt 694820.29

它给了我这个 Overlay graph

3 个答案:

答案 0 :(得分:2)

您似乎试图将两个不同y尺度上的两个变量绘制到一个图表上。我建议不要这样做,这被认为是不好的做法。例如,请参阅@hadley' s(ggplot2的作者)回答此类问题:https://stackoverflow.com/a/3101876/3022126

如果它们具有可比较的比例,则可以在一个 y轴上绘制两个变量,但两个数据集的范围不会大大重叠。

考虑其他可视化,可能使用两个单独的图表。

答案 1 :(得分:2)

使用ggplot,我会做一些像这样的事情。他们分别绘制了两组数据。第一个将数据排列到一个数据帧中,然后使用facet_wrap()并排放置绘图。第二个单独生成两个绘图对象,然后将两个绘图和图例组合成一个组合绘图。

但如果你真的需要"双y轴"方法,然后与一些摆弄,并使用情节'布局和gtable函数,可以完成(using code borrowed from here)。

喜欢这样:

library(ggplot2)
library(gtable)
library(plyr)

df1 <- data.frame(Tier = rep(1:5, each = 2),
       y = c(9, 1, 340, 417, 97, 156, 812, 3063, 4271, 11314),
       gp = rep(0:1, 5))

df2 <- read.table(text = "
    Tier    variable    value
   1   Opp_Amt 16200.00
   2   Opp_Amt 116067.50
   3   Opp_Amt 35284.12
   4   Opp_Amt 278107.10
   5   Opp_Amt 694820.29", header = TRUE)


dfA = df1
dfB = df2
names(dfA) = c("Tier", "Value", "gp")
dfA$var = "Task Ratio"
dfB = dfB[,c(1,3)]
dfB$gp = 3
dfB$var = "Total Opportunity Amount"
names(dfB) = names(dfA)
df = rbind(dfA, dfB)
df$var = factor(df$var)
df$var = factor(df$var, levels = rev(levels(df$var)))

 ggplot(df, aes(Tier, Value, fill = factor(gp))) +
    geom_bar(position = "stack", stat = "identity") +
    facet_wrap( ~ var, scale = "free_y") +
    scale_fill_manual("Group", breaks = c("0","1"), values = c("#F8766D", "#00BFC4", "black")) +
    theme_bw() +
    theme(panel.spacing = unit(2, "lines"),
          panel.grid = element_blank()) 



或者这个:

p1 <- ggplot(df1, aes(factor(Tier), y, fill = factor(gp))) +
   geom_bar(position = "stack", stat = "identity") +
   #guides(fill = FALSE) +
   scale_y_continuous("Task Ratio",
     limit = c(0, 1.1*max(ddply(df1, .(Tier), summarise, sum = sum(y)))), 
     expand = c(0,0)) +
   scale_x_discrete("Tier") +
   theme_bw() +
   theme(panel.grid = element_blank())

p2 <- ggplot(df2, aes(factor(Tier), value)) +
   geom_bar(stat = "identity") +
   scale_y_continuous("Total Opportunity Amount", limit = c(0, 1.1*max(df2$value)),  expand = c(0,0)) +
   scale_x_discrete("Tier") +
   theme_bw() +
   theme(panel.grid = element_blank())    

# Get the ggplot grobs,
# And get the legend from p1
g1 <- ggplotGrob(p1)
leg = gtable_filter(g1, "guide-box")
legColumn = g1$layout[which(g1$layout$name == "guide-box"), "l"]
g1 = g1[,-legColumn]
g2 <- ggplotGrob(p2)

# Make sure the width are the same in g1 and g2
library(grid)
maxWidth = unit.pmax(g1$widths, g2$widths)

g1$widths = as.list(maxWidth)
g2$widths = as.list(maxWidth)

# Combine g1, g2 and the legend
library(gridExtra)
grid.arrange(arrangeGrob(g2, g1, nrow = 1), leg,
   widths = unit.c(unit(1, "npc") - leg$width, leg$width), nrow=1)



或双y轴方法(但不推荐@ Phil的帖子中提到的原因):

width1 = 0.6       # width of bars in p1
width2 = 0.2       # width of bars in p2
pos = .5*width1 + .5*width2    # positioning bars in p2

p1 <- ggplot(df1, aes(factor(Tier), y, fill = factor(gp))) +
   geom_bar(position = "stack", stat = "identity", width = width1) +
   guides(fill = FALSE) + 
   scale_y_continuous("", 
     limit = c(0, 1.1*max(ddply(df1, .(Tier), summarise, sum = sum(y)))), 
     expand = c(0,0)) +
   scale_x_discrete("Tier") +
   theme_bw() +
   theme(panel.grid = element_blank(),
         axis.text.y = element_text(colour = "red", hjust = 0, margin = margin(l = 2, unit = "pt")),
         axis.ticks.y = element_line(colour = "red"))

p2 <- ggplot(df2, aes(factor(Tier), value)) +
   geom_blank() +
   geom_bar(aes(x = Tier - pos), stat = "identity", width = width2) +
   scale_y_continuous("", limit = c(0, 1.1*max(df2$value)),  expand = c(0,0)) +
   theme_bw() +
   theme(panel.grid = element_blank())

# Get ggplot grobs
g1 <- ggplotGrob(p1)
g2 <- ggplotGrob(p2)

# Get locations of the panels in g1
pp1 <- c(subset(g1$layout, name == "panel", se = t:r))

## Get bars from g2 and insert them into the panel in g1
g <- gtable_add_grob(g1, g2$grobs[[which(g2$layout$name == "panel")]][[4]][[4]], pp1$t, pp1$l)

# Grab axis from g1, reverse elements, and put it on the right
index <- which(g1$layout$name == "axis-l")
grob <- g1$grobs[[index]]
axis <- grob$children[[2]]
axis$widths <- rev(axis$widths)
axis$grobs <- rev(axis$grobs)
axis$grobs[[1]]$x <- axis$grobs[[1]]$x - unit(1, "npc") + unit(3, "pt")

g <- gtable_add_cols(g, g1$widths[g1$layout[index, ]$l], pp1$r)
g <- gtable_add_grob(g, axis, pp1$t, pp1$l+1)

# Grab axis from g2, and put it on the left
index <- which(g2$layout$name == "axis-l")
grob <- g2$grobs[[index]]
axis <- grob$children[[2]]
g <- gtable_add_grob(g, rectGrob(gp = gpar(col = NA, fill = "white")), pp1$t-1, pp1$l-1, pp1$b+1)
g <- gtable_add_grob(g, axis, pp1$t, pp1$l-1)

# Add axis titles
# right axis title
RightAxisText = textGrob("Task Ratio", rot = 90, gp = gpar(col = "red"))
g <- gtable_add_cols(g, unit.c(unit(1, "grobwidth", RightAxisText) + unit(1, "line")), 5)
g <- gtable_add_grob(g, RightAxisText, pp1$t, pp1$r+2)

# left axis title
LeftAxisText = textGrob("Total Opportunity Amount", rot = 90)
g <- gtable_add_grob(g, LeftAxisText, pp1$t, pp1$l-2)
g$widths[2] <- unit.c(unit(1, "grobwidth", LeftAxisText) + unit(1, "line"))

# Draw it
grid.newpage()
grid.draw(g)

enter image description here

答案 2 :(得分:0)

尝试查看add的{​​{1}}参数。

barplot

enter image description here