R语言 如何在ggplot中调整列文本以将数据值绑定到条形图的适当列

u59ebvdq  于 2023-05-20  发布在  其他
关注(0)|答案(2)|浏览(96)

我试着用这段代码来绘制这样的数据:

ammount <- c(1000, 3000, 1000, 5000, 4000, 1500, 2000, 2500, 4500, 5000, 1500, 6000)
area <- c("A", "B", "C", "D", "E", "F", "A", "B", "C", "D", "E", "F")
type <- c("incoming","incoming","incoming","incoming","incoming","incoming", 
          "outgoing", "outgoing", "outgoing", "outgoing", "outgoing", "outgoing")

df <- data.frame(area, ammount, type)

library(ggplot2)
library(magrittr)
library(scales)

df %>% 
  ggplot(aes(reorder(area, ammount), ammount,
             group = type,
             fill = type))+
  geom_col(position = "dodge")+
  scale_y_continuous(labels = comma_format(big.mark = ".",
                                           decimal.mark = ","))+
  theme(axis.text.x = element_text(vjust = 1, 
                                   hjust=1))+
  geom_text(aes(label = ammount), 
            size = 3, 
            position = position_stack(vjust = 0.5))+
  coord_flip()

我得到的是这个图:

我的问题是:
1.如何调整列文本(或标签)以将正确值绑定到适当列,
1.如何格式化文本使其可见,
1.是否可以使用除ggplot之外其他软件包。
提前感谢

k5ifujac

k5ifujac1#

1.在下面找到我的解决方案,在geom_text(..., position, ...)中使用position_dodge(0.905)作为position参数的值
theme()在代码中与vjust=1, hjust=1无关,因为vjust=1, hjust=1已经是默认值。

df %>% 
  ggplot(aes(reorder(area, ammount), ammount,
             group = type,
             fill = type))+
  geom_col(position = "dodge")+
  scale_y_continuous(labels = comma_format(big.mark = ".",
                                           decimal.mark = ",")) +
  geom_text(aes(label = ammount), 
            size = 3, 
            position = position_dodge(0.905)) +
  coord_flip()

  1. geom_text()有其他参数,如color, alpha,用于更改tex的颜色和可见性
df %>% 
  ggplot(aes(reorder(area, ammount), ammount,
             group = type,
             fill = type))+
  geom_col(position = "dodge")+
  theme(axis.text.x = element_text(vjust = 1, hjust=1))+
  scale_y_continuous(labels = comma_format(big.mark = ".",
                                           decimal.mark = ",")) +
  geom_text(aes(label = ammount), 
            size = 3, 
            position = position_dodge(0.8),
            color = 'darkblue',
            alpha = 1) +
  coord_flip()


可以找到更多文档here

  1. ggplot2可能是完成这项任务的最佳软件包,但如果您需要交互式绘图,则可以考虑plotlydygraph
oknwwptz

oknwwptz2#

你可以试试这样的方法:

library(ggplot2)
library(magrittr)
library(scales)

df %>% 
  ggplot(aes(reorder(area, ammount), ammount,
             group = type,
             fill = type,
             # added label here
             label = ammount))+
  geom_col(position = "dodge")+
  scale_y_continuous(labels = comma_format(big.mark = ".",decimal.mark = ","))+
  theme(axis.text.x = element_text(vjust = 1, hjust=1))+
  # question 1, center labels, question 2, size to make more visible
  geom_text(position = position_dodge2(width = 0.9, preserve = "single"), size = 5)+
  xlab('area') +
  coord_flip()

结果:

对于你的第三个问题,有一个基数R,或者plotly用于交互式绘图。我很喜欢ggplot2,所以我不会搜索其他软件包。

相关问题