ggplot2我正在使用一个小 dataframe进行绘图df。我的数据框有一个组变量和Letter两个数值变量(我在本文末尾包含了的版本)。XYdput()df
当我尝试对齐顶部条形的标签时,出现了我的主要问题。由于我的设计,一个变量需要显示在右侧,另一个变量需要显示在左侧。这就是为什么我将一些值乘以-1。这是我的绘图的代码和输出:
library(tidyverse)
library(ggplot2)
#Plot
df %>%
pivot_longer(-c(Letter)) %>%
mutate(value=ifelse(name=='X',value*-1,value)) %>%
ggplot(aes(x=Letter,y=value,fill=name))+
geom_bar(stat = 'identity',color='black',alpha=0.7)+
geom_text(aes(label=format(abs(value),big.mark = '.')),
size=3,fontface='bold')+
scale_x_discrete(limits = rev(unique(df$Letter)))+
scale_y_continuous(labels = function(x) scales::comma(abs(x)),
breaks = scales::pretty_breaks(10))+
coord_flip()
Run Code Online (Sandbox Code Playgroud)
和输出:
正如你所看到的,情节很好,但问题出在标签上。在左侧和右侧,标签的一部分位于条形内部,另一部分位于条形外部。我想在每个栏顶部的两侧都有标签。我不知道这是否可能,因为有些值是正值,有些是负值。我尝试添加hjust,geom_text()这只适用于左侧:
#Plot 1
df %>%
pivot_longer(-c(Letter)) %>%
mutate(value=ifelse(name=='X',value*-1,value)) %>%
ggplot(aes(x=Letter,y=value,fill=name))+
geom_bar(stat = 'identity',color='black',alpha=0.7)+
geom_text(aes(label=format(abs(value),big.mark = '.')),
size=3,fontface='bold',
hjust=1)+
scale_x_discrete(limits = rev(unique(df$Letter)))+
scale_y_continuous(labels = function(x) scales::comma(abs(x)),
breaks = scales::pretty_breaks(10))+
coord_flip()
Run Code Online (Sandbox Code Playgroud)
输出:
我想找到一种方法,使两侧的标签与各自栏的顶部对齐。
非常感谢您的帮助。我的数据dput()如下:
#Data
df <- structure(list(Letter = c("A", "B", "C", "D", "E", "F", "G",
"H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S"),
X = c(3099, 14201, 18901, 17351, 29498, 28928, 32284, 31536,
25334, 20008, 39242, 35856, 43317, 53765, 44652, 32876, 26142,
18567, 8836), Y = c(9482, 22669, 11159, 9506, 12113, 12805,
10570, 10199, 9190, 9217, 10674, 10894, 11986, 15664, 12793,
10552, 8050, 8609, 7717)), row.names = c(NA, -19L), class = c("tbl_df",
"tbl", "data.frame"))
Run Code Online (Sandbox Code Playgroud)
您实际上可以将 设为hjust美学变量,而不是为所有标签提供相同的 hjust 值。只需通过在调用hjust = value < 0 内部进行操作,将 1 指定为负值,将 0 指定为正值aes- 生成的逻辑向量将隐式转换为 1 和 0:
df %>%
pivot_longer(-c(Letter)) %>%
mutate(value = ifelse(name == 'X', value * -1, value)) %>%
ggplot(aes(x = Letter, y = value, fill = name)) +
geom_bar(stat = 'identity', color = 'black', alpha = 0.7) +
geom_text(aes(label = format(abs(value), big.mark = '.'), hjust = value < 0),
size = 3, fontface = 'bold') +
scale_x_discrete(limits = rev(unique(df$Letter))) +
scale_y_continuous(labels = function(x) scales::comma(abs(x)),
breaks = scales::pretty_breaks(10)) +
coord_flip()
Run Code Online (Sandbox Code Playgroud)