简体   繁体   中英

How to change legend values on ggplot pie chart?

I have built this particular table in R to build a pie chart using the ggplot package.

column,value,proportion,ypos,end,start,middle,hjust,vjust,legend
Urban,268053,97.78067170794165,48.890335853970825,6.143740798014896,0,3.071870399007448,0,1,Urban - 97.78 %
Rural,1296,0.4727563225686427,98.01704986922597,6.173444953813291,6.143740798014896,6.158592875914094,1,0,Rural - 0.47 %
Suburban,4788,1.746571969489708,99.12671401525515,6.283185307179586,6.173444953813291,6.228315130496439,1,0,Suburban - 1.75 %

However, I want all values in the legend column and NOT the column column to be printed in the legend because the legend variables are just too cramped together if I decide to label them in the pie chart. I also would like to change the legend title.

在此处输入图像描述

Below is the code I have used to build this graph.

library(ggplot2)
library(readr)
library(readxl)

demographics <- read_csv("C:\\path to file\\demographics.csv")

ggplot(demographics) + 
  geom_arc_bar(aes(x0 = 0, y0 = 0, r0 = 0, r = 1,
                   start = start, end = end, fill = column)) +
  coord_fixed() +
  scale_x_continuous(limits = c(-1.5, 1.4),  # Adjust so labels are not cut off
                     name = "", breaks = NULL, labels = NULL) +
  scale_y_continuous(limits = c(-1, 1),      # Adjust so labels are not cut off
                     name = "", breaks = NULL, labels = NULL) +
  scale_color_manual(name = "Community Type", labels = c(legend)) +
  ggtitle("Percentage of Population by Type of Community")

Can anybody assist me on this? Thanks in advance.

Try this:

library(ggplot2)
library(readr)
library(readxl)
library(ggforce)

ggplot(demographics) + 
  geom_arc_bar(aes(x0 = 0, y0 = 0, r0 = 0, r = 1,
                   start = start, end = end, fill = legend)) +
  coord_fixed() +
  scale_x_continuous(limits = c(-1.5, 1.4),  # Adjust so labels are not cut off
                     name = "", breaks = NULL, labels = NULL) +
  scale_y_continuous(limits = c(-1, 1),      # Adjust so labels are not cut off
                     name = "", breaks = NULL, labels = NULL) +
  scale_color_manual(name = "Community Type", labels = c(legend)) +
  ggtitle("Percentage of Population by Type of Community")+
  guides(fill=guide_legend(title="New Legend Title"))

Output:

在此处输入图像描述

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