Geom_text值重叠

时间:2019-07-25 16:36:01

标签: r geom-bar geom-text

我试图创建一个饼图,但是值彼此重叠。

样本数据:

City_Area   Age   Spending
   A       0-15    100
   A       15-30   400
   B       0-15    200
   B       15-30   300

这是我的代码:

CA = filter(City_Area == 'A') %>% group_by(City_Area,Age,Spending)

ggplot(CA, aes(x="",y = Spending, fill = Age)) + geom_bar(stat='identity')+ coord_polar("y") + theme_void() + geom_text(aes(label = scales::percent(round((..count..)/sum(..count..),2)),y= ((..count..)/sum(..count..))), stat="count",position=position_stack(0.5))

PieValueStack

这里没有coord_polar

Barchart without coord_polar

Using Rui Barradas code

1 个答案:

答案 0 :(得分:0)

数据准备代码似乎是错误的,绘图代码也是如此。

首先,准备数据。主要要做的是摆脱美元符号。我将使用sub来做到这一点。

library(dplyr)
library(ggplot2)

CA2 <- CA %>% 
  mutate(Spending = as.numeric(sub("\\$", "", Spending))) %>%
  filter(City_Area == 'A')

问题中有group_by行,但在此示例中不需要。

现在是情节。

ggplot(CA2, aes(x = "", y = Spending, fill = Age)) +
  geom_bar(stat = 'identity') + 
  coord_polar("y") + 
  theme_void() + 
  geom_text(aes(label = scales::percent(Spending/sum(Spending), 2)), 
            position = position_stack(0.5))

enter image description here

数据。

CA <- read.table(text = "
City_Area   Age   Spending
A       0-15    100$
A       15-30   400$
B       0-15    200$
B       15-30   300$
", header = TRUE)