Hi all,
I can't figure out how to specify the order with which the slices of a pie charts are supposed to be drawn.
I created a "label" field in my dataframe as I want these to be used in the legend. The problem is that
the slices are being ordered according to the "alphabetic" order of labels even though I'd like the slices being ordered as they appear (Very high, high, intermediate, low).
Here below the script I wrote.
contamination <- c('Very High','High','Intermediate','Low')
percentage <- c(50, 20, 5,25)
label <- c('50% Very high', '20% High','5% Intermediate','25% Low')
df<-data.frame(contamination, percentage,label)
pie_contamination<-ggplot(df,aes(x=2,y=percentage,fill=label))+
geom_bar(width=1,stat="identity",color="white") +
coord_polar(theta="y",start=0,direction=-1)+
theme_void()+
theme(legend.title=element_blank(),legend.text = element_text(size = 20,color="#58585A"))+
scale_fill_manual(values = c('blue','red','black','green'))+
annotate("text",x=0,y=0,label=" ",colour="#009999",size=14)
Welcome to the community!
You can try something like this:
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
library(ggplot2)
contamination <- c('Very High', 'High', 'Intermediate', 'Low')
percentage <- c(50, 20, 5, 25)
label <- c('50% Very high', '20% High', '5% Intermediate', '25% Low')
df <- data.frame(contamination, percentage, label,
stringsAsFactors = FALSE)
df %>%
mutate(contamination = factor(x = contamination,
levels = contamination), # ideally you should specify the order explicitly
label = factor(x = label,
levels = label)) %>% # same as above note
ggplot(mapping = aes(x = 2,
y = percentage,
fill = label)) +
geom_bar(width = 1,
stat = "identity") +
coord_polar(theta = "y",
start = 0,
direction = -1) +
theme_void() +
theme(legend.title = element_blank(),
legend.text = element_text(size = 20,
color = "#58585A")) +
scale_fill_manual(values = c('blue', 'red', 'black', 'green')) +
annotate(geom = "text",
x = 0,
y = 0,
label = " ",
colour = "#009999",
size = 14)
Created on 2019-08-26 by the reprex package (v0.3.0)
Thanks a lot, it's working perfectly
system
Closed
September 3, 2019, 3:31am
4
This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.