gpt4 book ai didi

r - 水平 ggplot - 如何在条内定位数据标签

转载 作者:行者123 更新时间:2023-12-02 18:17:19 26 4
gpt4 key购买 nike

我试图将我的数据标签放置在 ggplot 水平条内,因为标签放置在条形末端时会被切断。我尝试了各种不同的方法,例如调整 hjust 位置,但标签在栏下消失,我什至尝试使用 xlim/scale_x_continuous 允许完全查看标签,但到目前为止一直失败。

library(tidyverse)
library(ggplot2)

mydf <- data.frame( Category = c("Approved transactions"),
Nov_21=c(11028),
Dec_21=c(31455),
Jan_22=c(44480))

mydf %>%
gather(Month, Total, -Category) %>%
mutate(Month = reorder(Month, row_number())) %>%
mutate(Category = reorder(Category, row_number())) %>%
ggplot(aes(Month, Total, fill = Month, group = Category)) +
geom_text(aes(label=Total), position=position_dodge(width=0.9), hjust= 0.25) +
geom_bar(stat = "identity", position = "dodge", width=0.5, fill="light blue") +
coord_flip() +
labs(x = "", y = "", title = "Approved Counter Transactions", subtitle = "3 Month View", legend=FALSE) +
theme_bw() +
theme(panel.grid.major.x = element_blank(),
panel.border = element_blank(),
plot.title = element_text(hjust = 0),
axis.text.x = element_text(size = 10, face = "bold"),
axis.text.y = element_text(size = 10, face = "bold"),
legend.position = "none")

enter image description here

最佳答案

或者您可以在条形图中输入计数

示例代码:

mydf %>%
gather(Month, Total, -Category) %>%
mutate(Month = reorder(Month, row_number())) %>%
mutate(Category = reorder(Category, row_number())) %>%
ggplot(aes(Month, Total, fill = Month, group = Category)) +
geom_bar(stat = "identity", position = "dodge", width=0.5, fill="light blue") +
geom_text(aes(label=Total),position = position_dodge(width = .4),hjust=1.3, size = 10)+
labs(x = "", y = "", title = "Approved Counter Transactions", subtitle = "3 Month View", legend=FALSE) +
theme_bw() +
theme(panel.grid.major.x = element_blank(),
panel.border = element_blank(),
plot.title = element_text(hjust = 0),
axis.text.x = element_text(size = 10, face = "bold"),
axis.text.y = element_text(size = 10, face = "bold"),
legend.position = "none")

情节:enter image description here

关于r - 水平 ggplot - 如何在条内定位数据标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71408547/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com