【问题标题】:R: ggplot2 & Plotly: Recreating 'reference bands' on bar graphs from Tableau in RR:ggplot2 & Plotly:在 R 中的 Tableau 中重新创建条形图上的“参考带”
【发布时间】:2016-11-13 17:31:53
【问题描述】:

我正在尝试重新创建一些我每天在 Tableau for R 中使用的功能(ggplot2 和 plotly)。我需要能够创建类似于下图的参考带和线。我已经弄清楚如何从 geom_errorbar() 创建参考线。但是我似乎找不到“参考带”的解决方案。

如果在 ggplot2 或 plotly 中无法找到解决方案,我会打开另一个包,但我需要一些静态的 Rmarkdown 报告和一些动态的 html 小部件仪表板。

下面我有一些示例代码,我想为每个人的条形图添加“高”和“低”的参考波段。

library(ggplot2)

#Create Data
Name <- c("Rick","Carl","Daryl","Glenn")
Pos <- c("M","M","D","D")
Load <- c(100,110,90,130)
High <- c(150,160,130,140)
Low <- c(130,145,120,130)
data <- data.frame(Name,Pos,Load,High,Low)
rm(Name,Pos,Load,High,Low)


#create plot
ggplot(data = data, aes(x = Name, y = Load)) +
    geom_bar(stat ="identity", width=.4) 

如有任何指导,将不胜感激。谢谢!

【问题讨论】:

  • 给我们一个可重复的例子(数据和你的实际 ggplot 图)会让帮助你变得容易。
  • 谢谢,我会的。

标签: r ggplot2 plotly


【解决方案1】:

geom_rect() 是比geom_errorbar() 更好的选择,因为您可以复制您发布的相同图像。看看recterrorbar 纪录片。

以下示例可用于降价:

library(dplyr)
library(ggplot2)

delta <- 0.5
data <- mtcars %>% group_by(cyl, vs) %>%
  summarise(xmin = first(cyl) - 1,
            xmax = first(cyl) + 1,
            wt = mean(wt),
            ymin = wt - delta,
            ymax = wt + delta)

ggplot(data = data, aes(x = cyl, y = wt)) +
  geom_rect(aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax),
            fill = "indianred", alpha = 0.4) + # adds the reference band layer before
  geom_bar(stat = "identity", fill = "darkblue", width = 1) + # the bar layer
  facet_wrap(~vs) + theme_classic()

如果您只希望一个参考波段,您只需对所有观测值使用相同的 ymaxymin 参数。

您仍然需要在 html 版本中付出更多努力,因为 plotly::ggplotly() 搞砸了。

【讨论】:

  • 好的,我玩过你的解决方案。当 x 轴是连续的时,它是有意义的。我如何在 y 轴离散的情况下进行这项工作?我在顶部添加了一个数据集。
【解决方案2】:

我找到了解决方案。我需要将 xmin 和 xmax 设置为数字,然后我才能创建参考条。

library(ggplot2)

#Create Data
NameID <- c("Rick","Carl","Daryl","Glenn")
Pos <- c("M","M","D","D")
Load <- c(100,110,90,130)
High <- c(110,160,130,140)
Low <- c(90,145,120,130)
df <- data.frame(NameID,Pos,Load,High,Low)
rm(NameID,Pos,Load,High,Low)

p <- ggplot()
p <- p + scale_x_discrete()
p <- p + geom_rect(data=df, 
                       aes(xmin = as.numeric(NameID)-.25, 
                           xmax = as.numeric(NameID)+.25, 
                           ymin = Low, 
                           ymax = High),
                       fill = "blue", alpha = 0.2)
p <- p + geom_bar(data = df, aes(x = NameID, y = Load), stat="identity", width = .4)
p

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-29
    • 1970-01-01
    • 2017-03-02
    • 1970-01-01
    • 1970-01-01
    • 2021-01-18
    • 1970-01-01
    相关资源
    最近更新 更多