如何在 GGplot2 中向堆积条形图添加单个标签

2023-12-24

我想向 GGplot2 中的堆积条形图添加一个数字标签。

我有以下代码:

   # Load the packages
library(dplyr)
library(readr)
library(tidyr)
library(ggplot2)
library(RColorBrewer)

# Create a data set called M
M <- structure(list(X1 = c("Diversity", "Endangerment", "Marketability", "Total"),
B1 = c(5.1, 4.9, 4.7, 4.6), B2 = c(3.5, 
3, 3.2, 3.1), B3 = c(1.4, 1.4, 1.3, 1.5), Petal.Width = c(7.1, 
4.7, 3.2, 5.1)), .Names = c("X1", "B1", "B2", "B3", "B4"), row.names = c(NA, 
4L), class = "data.frame")
M

# Plot the stacked bar 
P <- M %>% 
  gather(variable, value, -X1) %>% 
  filter(X1!="Total") %>% #Removes total variable
  group_by(variable) %>% 
  mutate(sum=sum(value)) %>% 
  ungroup() %>% 
  mutate(variable=reorder(variable, -sum)) %>% #Reorders the chart based on breed total score
  ggplot(aes(variable, value, fill=X1, width =.7)) +
  geom_col(col="black") + #Black border around the bars
  expand_limits(y = 0) +
  scale_y_continuous(limits = c(0,70), breaks=c(0,10,20, 30,40, 50,60, 70), expand = c(0.02, 0.02))+
  geom_text(aes(label = sum), vjust = -.25)+ #Here the text is added
  scale_fill_brewer(palette="Dark2") + #Changes the colour scale
  labs(x="Breed",
       y="Weighted score",
       fill="") +
  theme_bw() +
  theme(panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        legend.direction="vertical", legend.position=c(0.9, 0.85), 
        legend.text=element_text(size=11),
        legend.key = element_rect(size = 4),
        legend.key.size = unit(1.5, 'lines'))  # Ensures spacing between the different lines on the legend.
P

我想尝试在每个条形上方包含“总和”值。我有什么想法如何去做这件事吗?


Answer

因此,我创建了另一个 data.frame,但使用 summarize 后我们将只有 1 个总和值。

Code

df <- structure(list(X1 = c("Diversity", "Endangerment", "Marketability", "Total"),
                B1 = c(5.1, 4.9, 4.7, 4.6), B2 = c(3.5, 
                                                   3, 3.2, 3.1), B3 = c(1.4, 1.4, 1.3, 1.5), Petal.Width = c(7.1, 
                                                                                                             4.7, 3.2, 5.1)), .Names = c("X1", "B1", "B2", "B3", "B4"), row.names = c(NA, 
                                                                                                                                                                                      4L), class = "data.frame")

df %>% 
  gather(variable, value, -X1) %>% 
  filter(X1!="Total") %>% 
  group_by(variable) %>% 
  mutate(sum=sum(value)) %>% 
  ungroup() %>% 
  mutate(variable=reorder(variable, -sum)) ->df

df %>% 
  group_by(variable) %>% 
  summarise(max = max(sum)) ->df_max

df %>% 
  ggplot(aes(variable, value, width =.7)) +
  geom_col(col="black",aes(fill=X1)) + #Black border around the bars
  expand_limits(y = 0) +
  scale_y_continuous(limits = c(0,70), breaks=c(0,10,20, 30,40, 50,60, 70),         expand = c(0.02, 0.02))+
  geom_text(data = df_max,
        aes(label = max, y = max), vjust = -.25)+ #Here the text is added
  scale_fill_brewer(palette="Dark2") + #Changes the colour scale
  labs(x="Breed",
       y="Weighted score",
       fill="") +
  theme_bw() +
  theme(panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(),
    legend.direction="vertical", legend.position=c(0.9, 0.85), 
    legend.text=element_text(size=11),
    legend.key = element_rect(size = 4),
    legend.key.size = unit(1.5, 'lines'))  # Ensures spacing between the different lines on the legend.

Out

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 GGplot2 中向堆积条形图添加单个标签 的相关文章

  • 在 R 的 for 循环中创建动态命名对象并分配动态值

    我正在尝试创建一套动态命名的新对象 例如 temp2015 使用 for 循环 并存储动态值 具体来说 其他对象的名称 例如 Y2015 和 for 循环中使用的值 例如 2015 在动态命名的新对象中 我不确定为什么下面的代码不起作用 Y
  • 从 data.frame 在 ggplot 图例中添加信息

    我想在图例中添加信息 哪个传感器具有该值 这是我的代码 z lt data frame a c sensor 1 sensor 2 sensor 3 sensor 4 sensor 5 sensor 6 sensor 7 sensor 8
  • 在包加载之前如何知道 R 中特定函数属于哪个包?

    例如 我知道许多流行的功能 例如tbl df 我通常不记得它属于哪个包 即data table or dplyr 所以我必须始终记住并加载一个包 但我做不到 tbl df除非我加载了正确的包 在 R 控制台本身加载或安装包之前 有没有办法知
  • data.table 抛出“找不到对象”错误[重复]

    这个问题在这里已经有答案了 我有一个数据表 library data table mydt lt data table index 1 10 当我在全局环境中尝试它时 我可以让它工作 但当我在调试器中或在包测试中使用它时却无法工作 问题是我
  • 在ggplot中设置y轴中断

    我在代码中设置中断时遇到困难 我尝试添加breaks seq 0 100 by 20 但似乎无法让它正常工作 本质上我希望 Y 轴从 0 到 100 每 20 个刻度一次 YearlyCI lt read table header T te
  • R:按组,测试一个变量的每个值是否存在于另一个变量中

    我有一个数据框架 结构如下 a lt c 1 1 1 2 2 2 3 3 3 3 4 4 b lt c 1 2 3 1 2 3 1 2 3 4 1 2 c lt c NA NA 2 NA 1 1 NA NA 1 1 NA NA df lt
  • R中IF函数的使用

    我正在短跑ifR 中的函数 但收到以下警告消息 In if runif 50 0 1 lt 0 69 the condition has length gt 1 and only the first element will be used
  • case_when 与部分字符串匹配和 contains()

    我正在使用一个数据集 其中有许多名为 status1 status2 等的列 在这些列中 它表示某人是否豁免 完整 注册等 不幸的是 豁免投入并不一致 这是一个示例 library dplyr problem lt tibble perso
  • 使用数据帧的 R 中的 EWMA 波动性

    我正在尝试从一系列股票每日收益中获取 EWMA 波动性 这些收益来自一个名为base retorno diario Data IBOV ABEV3 AEDU3 ALLL3 BBAS3 BBDC3 BBDC4 1 2000 01 04 0 0
  • 扩展数据框以使其具有与原始行中两列的范围一样多的行[重复]

    这个问题在这里已经有答案了 我有一个数据框如下 structure list symbol c u n v i a start c 9L 6L 10L 8L 7L end c 14L 15L 12L 13L 11L Names c symb
  • 计算 R 行中的非零条目数

    我有以下类型的数据 mode1 mode2 mode3 1 8 1 0 2 0 0 0 3 6 5 4 4 1 2 3 5 1 1 1 数据使用dput structure list mode1 c 8L 0L 6L 1L 1L mode2
  • rvest 函数 html_nodes 返回 {xml_nodeset (0)}

    我正在尝试抓取以下网站的数据框 http stats nba com game 0041700404 playbyplay http stats nba com game 0041700404 playbyplay 我想创建一个表格 其中包
  • 在 R 上安装 TDA 包时出错:目标“diag.o”的配方失败

    使用 Ubuntu 16 04 和 R 3 4 1 安装 R 包 TDA 时收到错误消息 它似乎与制作 CGAL diag cpp 和 或 diag o 最后的完整错误打印输出 有关 我仔细看了这个 在 R 上安装 TDA 包时出错 htt
  • 自定义轴缩放后 ggplot2 缺少标签

    我正在尝试使用我的 x 轴应用自定义缩放ggplot2 and scales trans new 但是 当我这样做时 一些轴标签丢失了 有人可以帮我弄清楚为什么吗 Setup library tidyverse the data ds lt
  • R 数据结构的运算效率

    我想知道是否有任何关于操作效率的文档R 特别是那些与数据操作相关的 例如 我认为向数据框添加列是有效的 因为我猜您只是向链接列表添加一个元素 我想添加行会更慢 因为向量保存在数组中C level你必须分配一个新的长度数组n 1并将所有元素复
  • 在闪亮的数据表中为每个单元格显示工具提示或弹出窗口?

    有没有什么方法可以为 r闪亮数据表中的每个单元格获取工具提示 有很多方法可以获取悬停行或列 但我找不到一种方法来获取行和列索引并为每个单元格显示不同的悬停工具提示 任何人都可以修改以下代码吗 library shiny library DT
  • 安装 2.15 后 ggplot2 中的 alpha 通道不起作用

    更新到 R 2 15 后 ggplot 中的 alpha 通道似乎不再起作用 plot rnorm 100 rnorm 100 bg cc000055 pch 21 工作得很好但是 qplot rnorm 100 rnorm 100 col
  • 使用“assign()”为列表项分配值

    首先了解一些背景 我写了一个中缀函数 本质上取代了这个习惯用法 x length x 1 lt y 或者简单地说x lt append x y 对于向量 这里是 lt function x y xcall lt substitute x x
  • 如何在R中分离两个图?

    每当我运行这段代码时 第一个图就会简单地覆盖前一个图 R中有没有办法分开得到两个图 plot pc title main abc xlab xx ylab yy plot pcs title main sdf xlab sdf ylab x
  • 闪亮井板宽度

    library shiny library shinydashboard ui lt dashboardPage dashboardHeader dashboardSidebar dashboardBody wellPanel tags d

随机推荐