简体   繁体   中英

How to change location of labels of pie chart in ggplot?

I am using this solution here: Adding values and percentages to pie chart

But my % are in the wrong place. How do I fix?

# Create dataframe of data
df = data.frame("Sectors" = c("Agriculture", "Industry", "Services"), # labels for your data
                "Values" = c(14.9, 48.0, 37.1)) # values of your data
display_color = c("#EB984E", "#1ABC9C", "#95A5A6") # colors for slices

# Create bar plot
g = ggplot(df, aes(x = "",
                   y = Values, # values for your slices
                   fill = Sectors
                   )
           )
g = g + geom_bar( # change the color of the slices
                 width = 1, # change width of bar
                 stat = "identity",
                 fill = display_color
                 )

# CONVERT TO PIE CHART
g = g + coord_polar("y", 
                    start = 0)
g = g + labs(x = NULL, y = NULL, fill = NULL, title = "GDP By Sector")
g

g = g  + theme(axis.line = element_blank(),
              axis.text = element_blank(),
              axis.ticks = element_blank(),
              plot.title = element_text(hjust = 0.5, 
                                        color = "#000000"),
              panel.background = element_blank()
              )

g = g + geom_text(aes(label = paste0(scales::percent(values / sum(values)))),
                    position = position_stack(vjust = .1))

g

在此处输入图片说明

The best thing to do is to remove the coord_polar() and see where the labels end up. That usually gives you a sense of what is wrong:

在此处输入图片说明

In this case, your labels are in the wrong order. If you add rev() to your labels, now we get the labels in the right order.

g = g + geom_text(aes(label = rev(paste0(scales::percent(Values / sum(Values))))),
                  position = position_stack(vjust = .1))

在此处输入图片说明

Here is the full pi chart.

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM