Percentage labels in pie chart with ggplot
Using mtcars
as example data. Maybe this what your are looking for:
library(ggplot2)
ggplot(mtcars, aes(x = "", fill = factor(cyl))) +
geom_bar(stat= "count", width = 1, color = "white") +
geom_text(aes(label = scales::percent(..count.. / sum(..count..))), stat = "count", position = position_stack(vjust = .5)) +
coord_polar("y", start = 0, direction = -1) +
scale_fill_manual(values = c("#00BA38", "#619CFF", "#F8766D")) +
theme_void()
Created on 2020-05-25 by the reprex package (v0.3.0)
Pie chart in ggplot2 and percentages
Use just sum
to count both genders. Example: percent(1000 / sum(df$value))
will return "4%"
.
library(tidyverse)
library(scales)
#>
#> Attaching package: 'scales'
#> The following object is masked from 'package:purrr':
#>
#> discard
#> The following object is masked from 'package:readr':
#>
#> col_factor
df <- data.frame(
group = c("Male", "Female"),
value = c(15000, 10000)
)
df
#> group value
#> 1 Male 15000
#> 2 Female 10000
ggplot(df, aes(x = "", y = value, fill = group)) +
geom_bar(width = 1, stat = "identity") +
coord_polar("y", start = 0) +
scale_fill_brewer("Blues") +
theme_void() +
geom_text(aes(
y = value / 2 + c(0, cumsum(value)[-length(value)]),
label = percent(value / sum(value))
), size = 5)
Created on 2021-09-22 by the reprex package (v2.0.1)
Putting percentage labels of a piechart in the legend using ggplot2
You can try this:
country<-c('Botswana','Botswana','Botswana','Botswana','Botswana','Botswana','Botswana','Botswana')
key<-c('Retail Margin','Wholesale Margin','BFP Component and Related Costs','Customs and Excise Tax','MVA Levy',"Fuel Tax","Petroleum Fund Levy","Road User Charge")
value<-c(0.0687,0.0577,0.7393,0.0031,0.01,0.0126,0.0141,0.0945)
data <-data.frame(country,key,value)
#Create variable
data$key2 <- paste0(data$key,' [',100*round(data$value,2),'%',']')
botswana <- ggplot(data, aes("", value, fill = key2)) +
geom_bar(stat = "identity", color = "white", size = 1) +
coord_polar(theta = "y") +
labs(colour = NULL) +
theme_void()
botswana <- botswana + theme(legend.title = element_blank())
R: Pie chart with percentage as labels using ggplot2
I've preserved most of your code. I found this pretty easy to debug by leaving out the coord_polar
... easier to see what's going on as a bar graph.
The main thing was to reorder the factor from highest to lowest to get the plotting order correct, then just playing with the label positions to get them right. I also simplified your code for the labels (you don't need the as.character
or the rep
, and paste0
is a shortcut for sep = ""
.)
League<-c("A","B","A","C","D","E","A","E","D","A","D")
data<-data.frame(League) # I have more variables
data$League <- reorder(data$League, X = data$League, FUN = function(x) -length(x))
at <- nrow(data) - as.numeric(cumsum(sort(table(data)))-0.5*sort(table(data)))
label=paste0(round(sort(table(data))/sum(table(data)),2) * 100,"%")
p <- ggplot(data,aes(x="", fill = League,fill=League)) +
geom_bar(width = 1) +
coord_polar(theta="y") +
annotate(geom = "text", y = at, x = 1, label = label)
p
The at
calculation is finding the centers of the wedges. (It's easier to think of them as the centers of bars in a stacked bar plot, just run the above plot without the coord_polar
line to see.) The at
calculation can be broken out as follows:
table(data)
is the number of rows in each group, and sort(table(data))
puts them in the order they'll be plotted. Taking the cumsum()
of that gives us the edges of each bar when stacked on top of each other, and multiplying by 0.5 gives us the half the heights of each bar in the stack (or half the widths of the wedges of the pie).
as.numeric()
simply ensures we have a numeric vector rather than an object of class table
.
Subtracting the half-widths from the cumulative heights gives the centers each bar when stacked up. But ggplot will stack the bars with the biggest on the bottom, whereas all our sort()
ing puts the smallest first, so we need to do nrow -
everything because what we've actually calculate are the label positions relative to the top of the bar, not the bottom. (And, with the original disaggregated data, nrow()
is the total number of rows hence the total height of the bar.)
How can I move the percentage labels outside of the pie chart in ggplot2?
It's a little bit of a hack, but you can specify the x-coordinate as slightly to the right of your normal barplot and then coord_polar will put it slightly outside when wrapping the bar graph into a pie chart. The default x-coordinate is 1, so using 1.5 places them right on the edge of the chart and 1.6 just barely outside the chart. All the code is basically the same, but note the new x=1.6
addition to the aes()
call of geom_text()
.
ggplot(data = df, aes(x="", y=proportion, fill=HPV)) +
geom_col(color = "black") +
coord_polar("y", start=0) +
geom_text(aes(x=1.6, label=paste0(round(proportion*100), "%")),
position = position_stack(vjust=0.5)) +
theme(panel.background = element_blank(),
axis.line = element_blank(),
axis.text = element_blank(),
axis.ticks = element_blank(),
axis.title = element_blank(),
plot.title = element_text(hjust = 0.5, size = 18)) +
ggtitle("Subtypes of HPV in GDC TCGA cervical cancer (CESC)") +
scale_fill_manual(values = c("#F46698","#F36DDB","#DD6DF3","#AC6DF3","#7355FC","#5562FC","#5562FC","#55B5FC","#55C7FC","#55E8FC","#56EDEB","#93F9EF","#61F9BF","#5BEC75","#58D64B","#91D64B","#B4D64B","#D6D64B","#FFDB57"))
ggplot: How to change labels to percentages on the graph?
You can change the label
in aes
to -
label = paste0(round(Protsent * 100, 1), '%')
Complete code -
library(ggplot2)
ggplot(merilen2, aes(y = Protsent, x = Aasta, color = tvs,
label = paste0(round(Protsent * 100, 1), '%')))+
geom_line()+
geom_point()+
ggrepel::geom_label_repel(label.size = 0,
label.padding = unit(0.3, "lines"),
size = 3,
min.segment.length = 0.2,
vjust=-0.5,
show.legend = F)+
scale_x_continuous(breaks = merilen2$Aasta, labels = merilen2$Aasta)+
labs(x = 'Aasta',
y = 'Protsent',
color = 'Töövõime staatus')
Removed scale_color_manual
because cen_cols
is not defined.
Related Topics
Applying Over a Vector of Functions
R - How to One Hot Encoding a Single Column While Keep Other Columns Still
Keep All Plot Components Same Size in Ggplot2 Between Two Plots
How to Write Data from R to Postgresql Tables with an Autoincrementing Primary Key
Directlabels: Avoid Clipping (Like Xpd=True)
Why Is Date Is Being Returned as Type 'Double'
Space Between Gpplot2 Horizontal Legend Elements
Split Concatenated Column to Corresponding Column Positions
Greek Letters in Ggplot Strip Text
How to Load Xlsx File Using Fread Function
Copying List of Files from One Folder to Other in R
Add Hline with Population Median for Each Facet
Shiny App File Upload: How to Save the Files Uploaded on a Shiny Gui to a Particular Destination
Ggplot2 2.1.0 Broke My Code? Secondary Transformed Axis Now Appears Incorrectly