有没有办法有一个barplot和使用barplot或ggplot在同一图形叠置barplot?(Is

2019-10-23 01:11发布

我有两个数据,我想覆盖到同一个情节。 我已经看了几个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)

它给了我这个

Answer 1:

使用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轴的方法 (但不建议在@菲尔的帖子给出的原因):

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)



Answer 2:

您似乎在试图绘制到一个图表上两个不同的Y标尺的两个变量。 我建议不要这样,这被认为是不好的做法。 见,例如,@hadley的(GGPLOT2的作者)在这里回答有关类似问题: https://stackoverflow.com/a/3101876/3022126

它可以绘制一个 y轴的两个变量,如果他们有相当的规模,但你的两个数据集的范围不会很大重叠。

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



Answer 3:

尝试寻找在add的参数barplot

## 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)



文章来源: Is there a way to have a barplot and a stacked barplot on the same graph using barplot or ggplot?