1
votes

I am fairly new to ggplot, so this probably is very simple question, but I just can't solve it. I use ggplot to build a pie chart based on a factor variable in a data frame. the variable levels are "F" and "M".

hcgen <- ggplot(hc, aes(x = factor(1), fill = gender))

Then I use a blank theme to visualize the chart

hcgen + geom_bar(width = 1) + coord_polar("y") + blank_theme + theme(axis.text.x=element_blank())

I have used different options to add labels but nothing works. I used for example:

geom_text(aes(y = value/3 + c(0, cumsum(value)[-length(value)]), + label = percent(value/100)), size=5)

but this gives the following error

Error in FUN(X[[i]], ...) : object 'value' not found

What am I doing wrong?

1
Is value defined in hc?SCDCE
No I got the geom_text from another topic on stack overflow. I think the problem is that I don't know how to define value.Bram
Ah I see where you copied that from, you need to scroll up to the top... df <- data.frame( group = c("Male", "Female", "Child"), value = c(25, 25, 50) )SCDCE
@Bram as @SCDCE pointed out earlier, do you have a variable named value in your data hc? The error message indicates that this value is not present in your data hc.mnm

1 Answers

1
votes

Looks like you are copying and pasting code where you don't know the data, in this instance the code you're working with is this:

library(ggplot2)
library(scales)

df <- data.frame(
 group = c("Male", "Female", "Child"),
 value = c(25, 25, 50))

bp <- ggplot(df, aes(x="", y=value, fill=group))+
  geom_bar(width = 1, stat = "identity")

pie <- bp + coord_polar("y", start=0)

blank_theme <- theme_minimal()+
  theme(
    axis.title.x = element_blank(),
    axis.title.y = element_blank(),
    panel.border = element_blank(),
    panel.grid=element_blank(),
    axis.ticks = element_blank(),
    plot.title=element_text(size=14, face="bold")
  )

pie + scale_fill_brewer("Blues") + blank_theme +
  theme(axis.text.x=element_blank())+
  geom_text(aes(y = value/3 + c(0, cumsum(value)[-length(value)]), 
                label = percent(value/100)), size=5)

Pie

Adding dplyr and some ggplot2 updates of course can streamline it:

library(dplyr)
library(ggplot2)
library(scales)

df <- data.frame(
  group = c("Male", "Female", "Child"),
  value = c(25, 25, 50))

df %>% 
  ggplot(aes(x="", y=value, fill=group)) +
  geom_col() +
  geom_text(aes(label = percent(value/100)), position = position_stack(vjust = 0.5)) +
  scale_fill_brewer(palette = "Blues") +
  coord_polar("y") + 
  theme_void() +
  labs(title = "TITLE",
       fill = "LEGEND")

update