Put labels on pie ggplot2 [duplicate] - r

This question already has answers here:
ggplot, facet, piechart: placing text in the middle of pie chart slices
(4 answers)
Closed 7 years ago.
My df looks like:
1 with score
125 without score
I'd like to make piechart in ggplot:
ggplot(data = df_pp, aes(x = "", y = Number/sum(Number),fill = PolyPhen_score)) + geom_bar(stat="identity") + coord_polar(theta='y') +
ggtitle("Variants with PolyPhen score and without PolyPhen score") +
scale_y_continuous(labels = percent) + labs(x = "", y = "") +
theme(panel.background = element_rect(fill = 'white')) +
geom_text(aes(label = paste(round(Number/sum(Number)*100),"%")),vjust = 5)
But my labels 1% and 99% are overlapped on the piechart.
If I add this code, it doesn't help:
geom_text(aes(y=Number/2 + c(0,cumsum(Number)[-length(Number)]), label = percent(Number/100)), size=5)

Maybe these other Stackoverflow questions can help you:
ggplot, facet, piechart: placing text in the middle of piechart slices
R + ggplot2 => add labels on facet pie chart
I did few tests on my machine with some random data and I tried with this:
geom_text(aes(x = 1.7, y=cumsum(Number/sum(Number)) - Number/sum(Number)/2, label = paste(round(Number/sum(Number)*100),"%")), size = 6)
X is the distance of labels from the center of the pie. x = 1.7 gives me a nice result with my data in RStudio, but probably you will need different values.

Related

how to fill pie chart with percentage value? [duplicate]

This question already has answers here:
ggplot, facet, piechart: placing text in the middle of pie chart slices
(4 answers)
Display percentage values on a pie chart [duplicate]
(1 answer)
R + ggplot2 => add labels on facet pie chart [duplicate]
(1 answer)
Closed 2 years ago.
I want to add percent value to this chart to this data frame
s<-# Basic piechart
ggplot(heart, aes(x="", y="", fill=sex)) +
geom_bar(stat="identity", width=1) +
coord_polar("y", start=0)
plot(s)
You haven't shared your data, but your plot code implies that heart is a data frame that includes a column labeled sex which is either of factor or character class, so this toy data set should suffice to demonstrate.
set.seed(1)
heart <- data.frame(sex = sample(c("Male", "Female"), 24, TRUE))
Your plotting code is actually stacking all the males, then all the females, without counting them, so there is no way for the geom_text to know where in this stack it should be plotting. Instead, you need to use the default stat of geom_bar, which is stat = "count", then plot the geom_text at the appropriate points:
library(ggplot2)
ggplot(heart, aes(x = "", fill = sex)) +
geom_bar(width = 1) +
geom_text(data = as.data.frame(table(heart$sex)),
aes(group = Var1, label = scales::percent(Freq / sum(Freq)),
y = Freq, fill = Var1),
position = position_stack(vjust = 0.5)) +
coord_polar("y", start = 0) +
theme_void()
#> Warning: Ignoring unknown aesthetics: fill
Created on 2020-11-19 by the reprex package (v0.3.0)

R version3.4.3: Overlapping labels in bar-plot in R (ggplot) [duplicate]

This question already has answers here:
How to maintain size of ggplot with long labels
(4 answers)
Closed 5 years ago.
I am trying to create a barplot but the labels overlap due to the length of the string. I tried shortening the names of the strings but that changes the underlying order. When I manually try to set the order using levels I get a bunch of NA.
ggplot(income_educa_copy, aes(x = factor(X_educag), fill = X_incomg))+
geom_bar(position = position_fill(reverse = TRUE)) +
ggtitle("Educational Achievement of Respondents") +
scale_fill_brewer("Income \nLevel",palette="Green",direction=-1) +
xlab("Educational Achievement") +
ylab("Proportion")
Below is the link of the image of the graph.
Bar Plot Image
ggplot(income_educa_copy, aes(x = factor(X_educag), fill = X_incomg))+
geom_bar(position = position_fill(reverse = TRUE)) +
ggtitle("Educational Achievement of Respondents") +
scale_fill_brewer("Income \nLevel",palette="Green",direction=-1) +
xlab("Educational Achievement") +
ylab("Proportion") +
theme(axis.text.x = element_text(angle = 45, hjust = 1))

Positioning values of stacked barchart in the center using ggplot2 [duplicate]

This question already has answers here:
Showing data values on stacked bar chart in ggplot2
(3 answers)
Closed 5 years ago.
I've created a stacked barchart and faceted using two variables. I'm unable to position the values in the barchart in the middle, it either appears at the extremes or overlaps. The expected image is the following:
I've pasted the script below. Any help would be appreciated.
library(dplyr)
library(reshape2)
library(ggplot2)
year<-c("2000","2000","2010","2010","2000","2000","2010","2010")
area<-c("Rural","Rural","Rural","Rural","Urban","Urban","Urban","Urban")
sex<-c("Male","Female","Male","Female","Male","Female","Male","Female")
city<-c(58,61,74,65,51,55,81,54)`
village<-c(29,30,20,18,42,40,14,29)
town<-c(13,9,6,17,7,5,5,17)
data<-cbind.data.frame(year,area,sex,city,village,town)
dre<-melt(data,id.vars = c("year","area","sex"))
dre <- arrange(dre,year,area,sex,variable) %>%
mutate(pos = cumsum(value) - (0.5 * value))
a <- ggplot(dre,aes(factor(sex),value,fill=variable)) +
geom_bar(stat='identity',position="stack")
b <- a +
facet_wrap(factor(year)~area)
c <- b +
geom_text(aes(label=paste0(value,"%"),y=pos),
position="stack",size=2,hjust=0.85,color="black")
d <- c +
coord_flip() +
theme_bw() +
scale_fill_brewer()
print(d)
You no longer need to calculate the position variable. Starting in ggplot2_2.2.0, text can be stacked and centered via position_stack.
The relevant line of geom_text code is below. Notice I don't need to use the "pos" variable at all for text placement.
geom_text(aes(label=paste0(value,"%")),
position = position_stack(vjust = .5), size = 2, color = "black")
The code for the plot and the resulting graph:
ggplot(dre, aes(factor(sex), value, fill = variable)) +
geom_col() +
facet_wrap(factor(year)~area) +
geom_text(aes(label = paste0(value,"%")),
position = position_stack(vjust = .5), size = 2, color = "black") +
coord_flip() +
theme_bw() +
scale_fill_brewer()

Moving legend to the bottom in ggplot2 [duplicate]

This question already has answers here:
How to move or position a legend in ggplot2
(4 answers)
Closed 7 years ago.
I have created the following heatmap. If you notice that the legend for cohort is on the right and the vertically placed.
How do I move the legend to the bottom in order to give more space for X axis variable month M0 to M55...Also, you will notice that X axis elements are overlapping hence not clear.
Output of the graph:
cohort.clients<-df1
cohort.clients$cohort<-as.character(cohort.clients$cohort)
#we need to melt data
cohort.chart.cl <- melt(cohort.clients, id.vars = 'cohort')
colnames(cohort.chart.cl) <- c('cohort', 'month', 'clients')
#define palette
reds <- colorRampPalette(c('light green',"dark green","yellow"))
#plot data
p <- ggplot(cohort.chart.cl, aes(x=month, y=clients, group=cohort))
p + geom_area(aes(fill = cohort)) +
scale_fill_manual(values = reds(nrow(cohort.clients))) +
ggtitle('Customer Cohort')
Try something like:
ggplot(cohort.chart.cl, aes(x=month, y=clients, group=cohort))
geom_area(aes(fill = cohort)) +
scale_fill_manual(values = reds(nrow(cohort.clients))) +
ggtitle('Customer Cohort') +
theme(axis.text.x = element_text(angle = 45, hjust = 1),
legend.direction = "horizontal", legend.position = "bottom"))
It's also worth noting that your color palette is essentially the same color. If you make cohort$month a factor then ggplot should automatically give you a much more informative palette by default. That being said, with >50 categories, you're well past the realm of a distinguishable colors and might also consider binning the months (into yearly quarters?) and returning to a spectrum like you have now.

R ggplot remove certain items from legend [duplicate]

This question already has answers here:
Turning off some legends in a ggplot
(2 answers)
Closed 4 years ago.
Is it possible to remove certain items from a legend created with ggplot? I have a plot that is faceted, and point sizes provide another dimension to the plot. Since the plot is faceted I do not need to have certain legend items since it is explained by the facet titles, but the legend is still relevant for the point size.
In the plot below I would like to remove the "AREA" legend items since it is already explained by the faceting, but keep the "TOTAL_VOLUME" legend items that explain the point sizes.
Here is the code used to generate the plot:
library(data.table) # Import libraries
library(ggplot2)
library(scales)
set.seed(1234) # Set Seed
area.list <- LETTERS[seq(1:7)] # 7 Possible areas
date.list <- seq(as.Date("2014/03/01"), by="month", length=13)
# Build a random data set
data <- data.table(AREA = sample(area.list, 80, replace=TRUE),
DATE = sample(date.list, 80, replace=TRUE),
VOLUME = rnorm(n=80, mean=100000,sd=40000),
NON_CONFORMING_VOLUME = rnorm(n=80, mean=30000,sd=5000))
# Summarise data by area and date
data <- data[, list(TOTAL_VOLUME=sum(VOLUME),
TOTAL_NC_VOLUME=sum(NON_CONFORMING_VOLUME)),
by=list(AREA, DATE)]
data$PERCENT_NC <- data$TOTAL_NC_VOLUME / data$TOTAL_VOLUME * 100
p <- ggplot(data = data, aes(x = DATE,
y = PERCENT_NC,
colour = AREA)) +
geom_point(aes(size = TOTAL_VOLUME)) +
geom_line() +
facet_grid(. ~ AREA) +
theme(legend.position="bottom", axis.text.x=element_text(angle=90,hjust=1)) +
ggtitle("Percent Non-Conforming by Area by Month") +
labs(x = "Month", y = "% Non-Conforming") +
scale_size_continuous(labels = comma)
plot(p)
I tried adding show_guide=FALSE to geom_point() but that removes both TOTAL_VOLUME and AREA.
Thank you
You can set the guide for each scale in the following way:
p + guides(size = "legend", colour = "none")

Resources