繁体   English   中英

有没有一种方法可以使用barplot或ggplot在同一张图上同时显示一个barplot和一个堆叠barplot?

[英]Is there a way to have a barplot and a stacked barplot on the same graph using barplot or ggplot?

我有两个要叠加到同一图上的数据。 我看过几本ggplot文章,但我认为ggplot中不可能。 所以我一直在使用barplot。 我有5层,我正在按层绘制总金额,以实线表示。

然后,我还有另一个数据,代表两种不同类型的工作人员在这些层中的任务数量。 我将其作为堆积的条形图。 但是我想在同一张图上显示它们,其中总美元金额为一个小节,然后在其旁边显示对应的堆叠小节。

这是情节: 按工作人员类型划分的全部任务的堆叠条形图

每层总美元条形图

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

        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

我想将图放在彼此的顶部,但条形图保持重叠,并且希望它们并排显示。

到目前为止的代码。

par(mar=c(2.5, 4, 4, 4)+2)
## Plot first set of data and draw its axis
barplot(data1$value, axes=FALSE,ylim=c(0,700000), xlab="", ylab="", 
        col="black",space=-10,main="Work Score")
axis(2, ylim=c(0,700000),col="black",las=1)  ## las=1 makes horizontal labels
mtext("Total Opportunity Amount",side=2,line=3.5)
box()

## Allow a second plot on the same graph
par(new=TRUE)

## Plot the second plot and put axis scale on right


m <- barplot(counts,  xlab="", ylab="", ylim=c(0,16000),axes=FALSE, col=c("red","darkblue"),space=3,width=0.5,density=20)
## a little farther out (line=4) to make room for labels
mtext("Task Ratio: Outbound to AE",side=4,col="red",line=3.5) 
axis(4, ylim=c(0,16000), col="red",col.axis="black",las=1)

这给了我 叠加图

看来您正在尝试在一张图表上绘制两个不同y比例的两个变量。 我建议您反对这样做,这被认为是不好的做法。 例如,请参见@hadley的(ggplot2的作者)在此处回答类似问题: https ://stackoverflow.com/a/3101876/3022126

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

考虑其他可视化效果,也许使用两个单独的图表。

使用ggplot ,我会做类似的事情之一。 他们分别绘制了两组数据。 首先将数据排列到一个数据帧中,然后使用facet_wrap()并排放置绘图。 第二种方法分别生成两个图对象,然后将两个图和图例组合成一个组合图。

但是,如果您确实需要“双y轴”方法,则可以进行一些摆弄,并使用绘图的布局和gtable函数,可以做到这一点( 使用从此处借来的代码 )。

像这样:

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)

在此处输入图片说明

尝试查看barplotadd参数。

## Function to create alpha colors for illustration.
col2alpha <- function(col, alpha = 0.5) {
  tmp <- col2rgb(col)
  rgb(tmp[1]/255, tmp[2]/255, tmp[3]/255, alpha)  
}

## Some fake data
dat1 <- data.frame(id = 1:4, val = c(10, 8, 6, 4))
dat2 <- data.frame(id = 1:4, val = c(4, 6, 8, 10))

barplot(dat1$val, col = col2alpha("blue"))
barplot(dat2$val, col = col2alpha("red"), add = TRUE)

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM