Just trying to fix this overlapped labeling:
My code:
values=c(164241,179670)
labels=c("Private", "Public")
colors=c("#cccccc", "#aaaaaa")
categoriesName="Access"
percent_str <- paste(round(graph$values / sum(graph$values) * 100,1), "%", sep="")
values <- data.frame(val = graph$values, Type = graph$labels, percent=percent_str )
pie <- ggplot(values, aes(x = "", y = val, fill = Type)) + geom_bar(width = 1) +
geom_text(aes(y = **val + 1**, **hjust=0.5**, **vjust=-0.5**, label = percent), colour="#333333", face="bold", size=10) +
coord_polar(theta = "y") + ylab(NULL) + xlab(NULL) +
scale_fill_manual(values = graph$colors) + labs(fill = graph$categoriesName) +
opts( title = graph$title,
axis.text.x = NULL,
plot.margin = unit(c(0,0,0,0), "lines"),
plot.title = theme_text(face="bold", size=14),
panel.background = theme_rect(fill = "white", colour = NA) )
print(pie)
Tried messing with the values marked with asterisks (** **) but haven't got anywhere.
Any help appreciated.
here is an example:
pie <- ggplot(values, aes(x = "", y = val, fill = Type)) +
geom_bar(width = 1) +
geom_text(aes(y = val/2 + c(0, cumsum(val)[-length(val)]), label = percent), size=10)
pie + coord_polar(theta = "y")
Perhaps this will help you understand how it work:
pie + coord_polar(theta = "y") +
geom_text(aes(y = seq(1, sum(values$val), length = 10), label = letters[1:10]))
Related
I was able to use patchwork to align two xaxis, but when I add ggbreak::scale_break(), it no longer aligns. What am I doing wrong here? Code of alignment issues follows. UnComment out scale_break() lines to see difference.
library(scales)
library(ggplot2)
library(ggbreak)
library(patchwork)
y <- as_tibble(c(rnorm(400,100,25),250) )
n= nrow(y)
cor = n/100
a.mean = mean(y$value)
a.median= quantile(y$value,0.5)
a.sd = sd(y$value)
binwidth = 5
upper.limit <- 260
plt1 <-ggplot(y, aes(x="", y = value) ) +
geom_boxplot(fill = "lightblue", color = "black", outlier.shape=NA) +
stat_boxplot(geom='errorbar',coef=NULL) +
stat_summary(fun=mean, geom="point", shape=23, size=7.6, color="black", fill = "blue") +
coord_flip() +
theme_classic() +
theme(panel.border = element_rect(color="black", fill = NA, size = 1),
axis.text = element_text(size=14)) +
xlab("") +
ylab("Value ($)") +
#scale_y_break(c(200,240 ) ) +
scale_y_continuous(breaks=pretty(c(0,upper.limit), n=10), limits=c(0,upper.limit) ) +
theme(axis.text.y=element_blank(),
axis.ticks.y=element_blank(),
axis.text.x.top=element_blank(),
axis.ticks.x.top=element_blank() )
plt2 <- ggplot(y, aes(x = value) ) +
geom_histogram(aes(y = (..count..)/sum(..count..)*100 ),
position = "identity", binwidth = 5,
fill = "lightblue", color = "black") +
stat_function(fun = function(x)
dnorm(x, mean = a.mean, sd = a.sd) * n * binwidth / cor,
color="darkblue", size =1) +
ylab("Percentage") +
xlab("") +
#scale_x_break(c(200,240 ) ) +
scale_x_continuous(breaks=pretty(c(0,upper.limit), n=10), limits=c(0,upper.limit) ) +
scale_y_continuous(breaks=seq(0,15, by=2.5)) +
theme(panel.border = element_rect(color="black", fill = NA, size = 1),
plot.title = element_text(hjust = 0.5),
text=element_text(size=20),
axis.text = element_text(size=14),
axis.text.x.top=element_blank(),
axis.ticks.x.top=element_blank() )
Fig01_01 <- plt2 / plt1 + plot_layout(nrow = 2, heights = c(10, 2) )
Fig01_01
One solution might be to manually/invisibly add in the y-axis labels and ticks for the bottom plot as exactly the same size as the upper plot. ggbreak does additionally seem to add in an immovable margin around the whole plotting area, so you may have some extra white space between plots doing it this way:
library(scales)
library(tidyverse)
library(ggbreak)
library(patchwork)
y <- as_tibble(c(rnorm(400,100,25),250) )
n= nrow(y)
cor = n/100
a.mean = mean(y$value)
a.median= quantile(y$value,0.5)
a.sd = sd(y$value)
binwidth = 5
upper.limit <- 260
plt1 <-ggplot(y, aes(x=1, y = value) ) +
geom_boxplot(fill = "lightblue", color = "black", outlier.shape=NA) +
stat_boxplot(geom='errorbar',coef=NULL) +
stat_summary(fun=mean, geom="point", shape=23, size=7.6, color="black", fill = "blue") +
coord_flip() +
theme_classic() +
theme(panel.border = element_rect(color="black", fill = NA, size = 1),
axis.text = element_text(size=14)) +
xlab(" ") +
ylab("Value ($)") +
scale_y_break(c(200,240 ) ) +
scale_y_continuous(breaks=pretty(c(0,upper.limit), n=10), limits=c(0,upper.limit) ) +
theme(axis.text.y=element_text(colour = "white", size = 14),
axis.ticks.y=element_line(colour = "white"),
axis.text.x.top=element_blank(),
axis.title.y=element_text(size=20),
axis.ticks.x.top=element_blank() )
plt2 <- ggplot(y, aes(x = value) ) +
geom_histogram(aes(y = (..count..)/sum(..count..)*100 ),
position = "identity", binwidth = 5,
fill = "lightblue", color = "black") +
stat_function(fun = function(x)
dnorm(x, mean = a.mean, sd = a.sd) * n * binwidth / cor,
color="darkblue", size =1) +
ylab("Percentage") +
xlab("") +
scale_x_break(c(200,240 ) ) +
scale_x_continuous(breaks=pretty(c(0,upper.limit), n=10), limits=c(0,upper.limit) ) +
scale_y_continuous(breaks=seq(0,15, by=2.5)) +
theme(panel.border = element_rect(color="black", fill = NA, size = 1),
plot.title = element_text(hjust = 0.5),
text=element_text(size=20),
axis.text = element_text(size=14),
axis.text.x.top=element_blank(),
axis.ticks.x.top=element_blank() )
Fig01_01 <- plt2 / plt1 + plot_layout(nrow = 2, heights = c(6, 2) )
Fig01_01
How can I transform this bar plot into a pie chart?
This is the bar plot I have:
This is the code I use to make the bar plot:
dados_gráfico_distrito <- dados_desde_2015 %>%
filter(!is.na(qsd_distrito_nascimento_rec)) %>%
group_by(anoletivo_cat) %>%
count(anoletivo_cat, qsd_distrito_nascimento_rec) %>%
mutate(pct = n / sum(n), pct_label = scales::percent(pct, accuracy=1))
dados_gráfico_distrito$qsd_distrito_nascimento_rec <- factor(dados_gráfico_distrito$qsd_distrito_nascimento_rec, levels = c("Other", "Porto", "Braga"))
ggplot(dados_gráfico_distrito, aes(x= anoletivo_cat, fill = qsd_distrito_nascimento_rec, y = pct)) +
geom_bar(position = "fill", stat="identity", width = 0.5) +
geom_text(aes(label = paste(pct_label), y = pct), position = position_fill(vjust = 0.5), colour = "black", size = 3.2) +
scale_y_continuous(labels = scales::percent) +
labs(y = " ", x = " ", fill=" ") +
theme_void() + scale_fill_brewer(palette="Paired") +
theme(legend.text = element_text(size = 8, colour = "black")) +
theme(axis.text = element_text(size = 8, colour = "black")) +
theme(legend.position = "bottom", legend.direction = "horizontal") +
guides(fill = guide_legend(reverse=TRUE)) +
theme(plot.margin = unit(c(1, 1, 1, 1), "cm")) +
theme(panel.grid = element_line(colour="grey90")) +
theme(panel.grid.minor.y = element_line(color = "white"), panel.grid.major.x = element_line(color = "white"))
When I try to transform it in a pie chart, adding the code line coord_polar () I get this chart:
This is what I pretend:
Thank you!
As you did not provide sample data, I have used some other sample data. Perhaps this will meet your needs. Please modify as necessary.
library(ggrepel)
library (ggplot2)
df = read.csv("https://www.dropbox.com/s/lc3xyuvjjkyeacv/inputpie.csv?dl=1")
df <- df %>% group_by(fac) %>%
mutate(
facc = ifelse(fac=="f1", "15/16 to 19/20", "20/21"),
cs = rev(cumsum(rev(per))),
text_yp = per/2 + lead(cs, 1),
text_yp = if_else(is.na(text_yp), per/2, text_yp)
) %>% data.frame()
df$type <- factor(df$type, levels=unique(df$type))
ggplot(df, aes(x="", y=per, fill=type )) +
geom_bar(stat="identity", width=1) +
coord_polar("y", start=0) +
facet_grid(facc~. ) +
scale_fill_brewer(palette="Paired") +
theme_void() +
geom_label_repel(
aes(label = text_y, y = text_yp), show.legend = FALSE
) +
scale_y_continuous(labels = scales::percent) +
labs(y = " ", x = " ", fill=" ") +
theme(legend.text = element_text(size = 8, colour = "black")) +
#theme(axis.text = element_text(size = 8, colour = "black")) +
#theme(legend.position = "bottom", legend.direction = "horizontal") +
guides(fill = guide_legend(reverse=TRUE)) +
theme(plot.margin = unit(c(1, 1, 1, 1), "cm")) +
theme(panel.grid = element_line(colour="grey90")) +
theme(panel.grid.minor.y = element_line(color = "white"), panel.grid.major.x = element_line(color = "white"))
How can I put the labels inside the plot without decimal cases, in both bars?
This is my code:
dados_gráfico_cursoanteriorsatisfação_PA <- PA_dados_desde_2015 %>%
filter(!is.na(qsd_3PA_curso_anterior_satisfação_rec)) %>%
group_by(anoletivo_cat) %>%
count(anoletivo_cat, qsd_3PA_curso_anterior_satisfação_rec) %>%
mutate(pct = n / sum(n), pct_label = scales::percent(pct))
dados_gráfico_cursoanteriorsatisfação_PA$qsd_3PA_curso_anterior_satisfação_rec <- factor(dados_gráfico_cursoanteriorsatisfação_PA$qsd_3PA_curso_anterior_satisfação_rec, levels = c("Very satisfied", "Satisfied", "Insatisfied", "Very insatified"))
ggplot(dados_gráfico_cursoanteriorsatisfação_PA, aes(x= anoletivo_cat, fill = qsd_3PA_curso_anterior_satisfação_rec, y = pct)) +
geom_bar(position = "fill", stat="identity", width = 0.5) +
geom_text(aes(label = paste(pct_label), y = pct), position = position_fill(vjust = 0.5), colour = "black", size = 3.2) +
scale_y_continuous(labels = scales::percent) +
labs(y = " ", x = " ", fill=" ") +
theme_void() + scale_fill_brewer(palette="Paired") +
theme(legend.text = element_text(size = 8, colour = "black")) +
theme(axis.text = element_text(size = 8, colour = "black")) +
theme(legend.position = "bottom", legend.direction = "horizontal") +
guides(fill = guide_legend(reverse=TRUE)) +
theme(plot.margin = unit(c(1, 1, 1, 1), "cm")) +
theme(panel.grid = element_line(colour="grey90")) +
theme(panel.grid.minor.y = element_line(color = "white"), panel.grid.major.x = element_line(color = "white"))
This is the plot I'm getting:
Thank you in advance! :)
I have data that looks like this, df_Filtered:
Product Relative_Value
Car 0.12651458
Plane 0.08888552
Tank 0.03546231
Bike 0.06711630
Train 0.06382191
I want to make a bar plot of the data in GGplot2:
ggplot(df_Filtered, aes(x = Product, y = Relative_Value, fill = Product)) +
scale_y_continuous(labels = scales::percent) +
geom_bar(stat = "identity") +
theme_bw() +
theme(plot.background = element_rect(colour = "black", size = 1)) +
theme(legend.position = "none") +
theme(plot.title = element_text(hjust = 0.5))
labs(x ="Product", y = "Percentage of total sell", title = "Japan 2010") +
theme(panel.grid.major = element_blank())
How do i get rid of the decimals on the y-axis in the chart? So that it says 20 % instead of 20.0 %?
Use percent_format from the scales package to set accuracy to 1.
library(ggplot2)
library(scales)
ggplot(df_Filtered, aes(x = Product, y = Relative_Value, fill = Product)) +
scale_y_continuous(labels = percent_format(accuracy = 1)) +
geom_bar(stat = "identity") +
theme_bw() +
theme(plot.background = element_rect(colour = "black", size = 1)) +
theme(legend.position = "none") +
theme(plot.title = element_text(hjust = 0.5)) +
labs(x ="Product", y = "Percentage of total sell", title = "Japan 2010") +
theme(panel.grid.major = element_blank())
DATA
df_Filtered <- read.table(text = "Product Relative_Value
Car 0.12651458
Plane 0.08888552
Tank 0.03546231
Bike 0.06711630
Train 0.06382191",
header = TRUE, stringsAsFactors = FALSE)
scales::percent_format(accuracy = 2) doesn't allow manual breaks = c(0, 0.5, .10).
So, I have to create the manual function scale_y_continuous(breaks = c(0, 0.5, .10), labels = function(x) paste0(round(as.numeric(x*100)), "%")) .
I would like to know if it's possible to modify the ticks of x axis with a ggplot pie chart.
Here what I can do :
# Some colors
couleurs <- data.frame(
id=seq(1,17,1),
mix=c(c(rep(1,6),rep(2,7),rep(3,4))),
html=c("#A00020","#109618","#388EE4","#C484D1","#FFAA33","#CCCDD0","#004AC5","#F80094","#CB5023","#638995","#33CFCF","#95DC4E","#F7D633","#5C403C","#F72020","#00D96C","#FDE4C5")
)
couleurs$html <- factor(couleurs$html, levels = couleurs$html[order(couleurs$id, decreasing = FALSE)])
# Data
activite <- data.frame(label=c("B to B","B to C","B to B / B to C", "B to B"), cible=c(rep("Externe",3), "Interne"), nb=c(12,9,3,12))
activite$label <- factor(activite$label, levels = activite$label[order(activite$nb[activite$cible=="Externe"], decreasing = TRUE)])
library(plyr)
activite<-ddply(activite,.(cible),transform,pc=(nb/sum(nb))*100)
activite
# Pie chart
library(ggplot2)
ggplot(data = activite, aes(x = "", y = nb, fill = label )) +
geom_bar(stat = "identity", position = position_fill(), width = 1) +
coord_polar(theta= "y", start = 0, direction = -1) +
labs(fill="") +
scale_fill_manual(values=as.character(couleurs$html[1:nrow(activite)]), labels=paste(activite$label,"\t\t\t",sep="")) +
geom_text(aes(label = paste(pc,"%", sep=" ")), size=4, colour = "white", fontface = "bold", position = position_fill(vjust = 0.5)) +
theme(strip.text = element_text(size=20, face = "bold", ), strip.background = element_rect(fill="grey75")) +
theme(panel.background = element_rect(fill = "white")) +
theme(plot.background = element_rect(fill = "grey92")) +
theme(legend.position="bottom", legend.background = element_rect(fill="grey92")) +
theme(legend.key = element_blank()) +
theme(panel.grid.minor = element_blank(), panel.grid.major = element_line(colour = "grey75")) +
theme(axis.text.y = element_blank()) +
theme(axis.ticks.length = unit(0, "mm")) +
theme(axis.title.x = element_blank(),axis.title.y = element_blank()) +
theme(legend.box.spacing = unit(1, "mm")) +
facet_wrap(~ cible)
Here my result:
After several hours of serach, I didn't find a solution to create what I want. The exact same pie chart but with personalised ticks like that :
With these particular conditions :
- do not change the direction of the data in the pie chart, I want it like exactly this
- if possible (but if not possible, it's okay), I would like the ticks' labels not superposed with the axis.
If someone can help me, I would really appreciate.
Here's one solution:
ggplot(data = activite %>%
group_by(cible) %>%
arrange(desc(nb)) %>%
mutate(axis.label = cumsum(nb),
axis.position = cumsum(pc)/100) %>%
mutate(axis.label = ifelse(pc == min(pc),
paste(axis.label, "0", sep = "-"),
axis.label)),
aes(x = 1, y = nb, fill = label )) +
geom_segment(aes(x = 1, xend = 1.6, y = axis.position, yend = axis.position),
colour = "grey75") +
geom_vline(xintercept = 1.6, colour = "grey75") +
geom_bar(stat = "identity", position = position_fill(reverse = T), width = 1) +
coord_polar(theta= "y", start = 0, direction = 1) +
labs(fill="") +
scale_fill_manual(values=as.character(couleurs$html[1:nrow(activite)]), labels=paste(activite$label,"\t\t\t",sep="")) +
geom_text(aes(label = paste(pc,"%", sep=" ")), size=4, colour = "white",
fontface = "bold", position = position_fill(vjust = 0.5, reverse = T)) +
geom_text(aes(x = 1.7, label = axis.label), size = 3,
position = position_fill(reverse = T)) +
theme(strip.text = element_text(size=20, face = "bold", ), strip.background = element_rect(fill="grey75")) +
theme(panel.background = element_rect(fill = "white")) +
theme(plot.background = element_rect(fill = "grey92")) +
theme(legend.position="bottom", legend.background = element_rect(fill="grey92")) +
theme(legend.key = element_blank()) +
theme(panel.grid = element_blank()) +
theme(axis.text = element_blank()) +
theme(axis.ticks = element_blank()) +
theme(axis.title = element_blank()) +
theme(legend.box.spacing = unit(1, "mm")) +
facet_wrap(~ cible)
Explanation:
The sequence in your labels went clockwise, while the direction of the polar coordinates went counter-clockwise. That makes labelling rather troublesome. I switched the direction for polar coordinates, & added reverse = T inside the position adjustment calls for the geoms.
It's hard to assign different axis breaks to different facets of the same plot, so I didn't. Instead, I modified the data to include calculated axis labels / margin positions, added margins via geom_segment / geom_vline, & hid the axis text / ticks in theme().