Legend of the x axis in two Lines - r

[enter image description here][1]I write because I have a doubt, I need the legend of the graphic to stay in two lines to give more visibility to the graphic. I am trying to add the following code but it does not work
[# creamos el gráfico base
ggplot(UNICOS , aes(x = NOMBRE_SERVICIO, y = ID_GESTION_ATENCION)) +
geom_bar(stat="identity") +
theme(axis.text.x=element_text(angle=90,hjust=1)) +
stat_pareto(point.color = "blue",
point.size = 2,
line.color = "black",
bars.fill = "#66CCFF")+
ggtitle("Pareto tipo trámite")+
theme(plot.title = element_text(hjust = 0.5)) +
ylab("Cantidad") +
xlab("")+
scale_y_continuous(sec.axis = sec_axis(~./(max(.) * 0.95) * 100, name = "%Acumulado"))+
theme(panel.border = element_blank(), panel.grid.major = element_blank(),
panel.grid.minor = element_blank(), axis.line = element_line(colour = "gray")) -> p
# Armamos las dos graficas
p1 <- p + scale_x_discrete(breaks = UNICOS$NOMBRE_SERVICIO\[1:10\]) + coord_cartesian(xlim = c(1, 10))

Add \n in the x variable names where you want the line breaks:
x.labels <- c("Notificación\naudiencia", "extraordinary long\nlong text", "text that cannot\nbe abbreviated\nby any means")
value <- c(10, 5, 3)
df <- data.frame(x.labels, value)
ggplot(df, aes(fill = 1, y = value, x = x.labels)) +
geom_bar(stat = "identity") +
theme(axis.text.x = element_text(angle = 90))

Related

How to set a conditional size scale based on name in ggplot?

Below is a simple bubble plot for three character traits (Lg_chr, Mid_chr, and Sm_chr) across three locations.
All good, except that because the range of Lg_chr is several orders of magnitude larger than the ranges for the other two traits, it swamps out the area differences between the smaller states, making the differences very difficult to see - for example, the area of the points for for Location_3's Mid_chr (70) and Sm_chr (5), look almost the same.
Is there a way to set a conditional size scale based on name in ggplot2 without having to facit wrap them? Maybe a conditional statement for scale_size_continuous(range = c(<>, <>)) separately for Lg_chr, Mid_chr, and Sm_chr?
test_df = data.frame(lg_chr = c(100000, 150000, 190000),
mid_chr = c(50, 90, 70),
sm_chr = c(15, 10, 5),
names = c("location_1", "location_2", "location_3"))
#reformat for graphing
test_df_long<- test_df %>% pivot_longer(!names,
names_to = c("category"),
values_to = "value")
#plot
ggplot(test_df_long,
aes(x = str_to_title(category),
y = str_to_title(names),
colour = str_to_title(names),
size = value)) +
geom_point() +
geom_text(aes(label = value),
colour = "white",
size = 3) +
scale_x_discrete(position = "top") +
scale_size_continuous(range = c(10, 50)) +
scale_color_manual(values = c("blue", "red",
"orange")) +
labs(x = NULL, y = NULL) +
theme(legend.position = "none",
panel.background = element_blank(),
panel.grid = element_blank(),
axis.ticks = element_blank()) ```
Edit:
You could use ggplot_build to manually modify the point layer [[1]] to specify the sizes of your points like this:
#plot
p <- ggplot(test_df_long,
aes(x = str_to_title(category),
y = str_to_title(names),
colour = str_to_title(names),
size = value)) +
geom_point() +
geom_text(aes(label = value),
colour = "white",
size = 3) +
scale_x_discrete(position = "top") +
scale_color_manual(values = c("blue", "red",
"orange")) +
labs(x = NULL, y = NULL) +
theme(legend.position = "none",
panel.background = element_blank(),
panel.grid = element_blank(),
axis.ticks = element_blank())
q <- ggplot_build(p)
q$data[[1]]$size <- c(7,4,1,8,5,2,9,6,3)*5
q <- ggplot_gtable(q)
plot(q)
Output:
You could use scale_size with a log10 scale to make the difference more visuable like this:
#plot
ggplot(test_df_long,
aes(x = str_to_title(category),
y = str_to_title(names),
colour = str_to_title(names),
size = value)) +
geom_point() +
geom_text(aes(label = value),
colour = "white",
size = 3) +
scale_size(trans="log10", range = c(10, 50)) +
scale_x_discrete(position = "top") +
scale_color_manual(values = c("blue", "red",
"orange")) +
labs(x = NULL, y = NULL) +
theme(legend.position = "none",
panel.background = element_blank(),
panel.grid = element_blank(),
axis.ticks = element_blank())
Output:

Label individual plots in facet_grid

I am trying to finish this graph, and what I need is to add the R-squared to each graph individually.
However, the labels are superimposed on each graph.
I used p + geom_text and p + geom_label without positive results.
Trajectories$date<-as.POSIXct(Trajectories$date,"%Y-%m-%d",tz = "UTC")
# Reorder names in a new variable
Trajectories$variable_f = factor(Trajectories$variable,
levels=c("canopy_cover", "Leaf_litter", "Chla", "Shrimps", "macroinvertebrates"))
levels(Trajectories$variable_f) <-
c("textstyle('Canopy openness')",
"textstyle('Leaf litter')",
"textstyle('Chlorophyll-')*italic('a')",
"textstyle('Shrimps')",
"atop(NA,atop(textstyle('Macroinvertebrate'),textstyle('density')))")
# Changes names in Facet_grid ---- es una manera buena, pero no la voy a usar --- Habria que labeller(variable_f = variable_f
#variable_f <- c("Canopy openness", "Leaf litter", "Chlorophyll-a","Shrimps","Macroinvertebrates")
#names(variable_f) <- c("canopy_cover", "Leaf_litter", "Chla", "Shrimps", "macroinvertebrates")
streams <- c("Prieta A", "Prieta B")
names(streams) <- c("QPA", "QPB")
# General graph -----------------------------------------------------------
p<- ggplot(Trajectories, aes(date,value)) +
geom_point(shape = 21, fill = "#bdd7e7", color = "#2171b5", size = 3) +
geom_smooth(se = T, size=1.7, color= "gray20", method = "gam", formula = y ~s(x)) +
geom_hline(yintercept = 0, color="gray20") +
xlab('Year') + ylab("Change in magnitude") +
theme(axis.title.x = element_text(size = 14, angle = 0)) + # axis x
theme(axis.title.y = element_text(size = 14, angle = 90)) + # axis 7
theme(axis.text.x=element_text(angle=0, size=10, vjust=0.5, color="black")) + #subaxis x
theme(axis.text.y=element_text(angle=0, size=10, vjust=0.5, color="black")) + #subaxis y
ylim(-3,3) +
theme(legend.position="none")+
theme(panel.grid.major = element_line(colour = "gray95"), panel.grid.minor = element_blank(),
panel.background = element_blank(), axis.line = element_line(colour = "black")) +
theme(panel.border = element_rect(colour = "black", fill=NA, size=0.5)) +
facet_grid(vars(stream), vars(variable_f),
labeller = labeller(variable_f = label_parsed, stream = streams)) +
theme(
strip.text.x = element_text(size = 10, color = "black"),
strip.text.y = element_text(size = 10, color = "black"),
strip.placement = "outside") +
theme(strip.background=element_rect(color= "black", fill="gray85")) +
theme(strip.text.x = element_text(margin = margin(0.001,0,0.001,0, "cm"))) +
geom_vline(aes(xintercept=as.POSIXct("2017-09-21")), # Hurricane Maria
col= "red",linetype=4, alpha=0.9) +
geom_vline(aes(xintercept=as.POSIXct("2017-09-6")), # Hurricane Irma
col= "blue",linetype=4, alpha=0.9)
p
I tried to build a data frame with the labels. But it doesn't work, and it overlaps the labels.
labels <- data.frame(variable =c("canopy_cover","Leaf_litter","Chla","Shrimps","macroinvertebrates",
"canopy_cover","Leaf_litter","Chla","Shrimps","macroinvertebrates"),
label=c("R1","R2","R3","R4","R5","R6","R7","R8","R9","R10"),
stream= c("QPA","QPA","QPA","QPA","QPA",
"QPB","QPB","QPB","QPB","QPB"))
labels
p + geom_text(
size = 5,
data = labels,
mapping = aes(x = as.POSIXct("2017-09-6"), y = Inf, label = label),
hjust = 1.05,
vjust = 1.5
)
Thanks in advance

Missing some legend items when using scale_color_binned(guide = guide_legend())

I use the following code to plot line graphs. When I convert the continuous color legend to discrete one, some of the legend keys are missing.
df <- data.frame(L = seq(from=30, t =300, by=10), Kg = rep(22427983, length=28),
t = rep(10, length=28), de = rep(3.33, length=28))
S <- c(8,10,12,14,16)
df <- merge(df,S)
colnames(df)[5] <- "S"
Span_M.E.M <- data.frame(df, Current = (0.77 + (df$de/9.1)) * (0.075 + (df$S/9.5)^0.6 *
(df$S/df$L)^0.2 * (df$Kg/(12 * df$L * (df$t)^3))^0.1), Updated =
0.1 + 1.15 * (0.77 + (df$de/9.1)) * (0.075 + (df$S/9.5)^0.6 *
(df$S/df$L)^0.2 * (df$Kg/(12 * df$L * (df$t)^3))^0.1))
ggplot(Span_M.E.M, aes(L, colour = S, group = S)) +
geom_line(aes(y = Current, linetype = "Current")) +
geom_line(aes(y = Updated, linetype = "Updated")) +
scale_color_gradient() +
labs(x = element_text("Span Length (ft)"), y = element_blank(),
title = paste("Moment Live Load Distribution Factors \n Exterior Girder - Multi Lane"),
linetype = element_blank(), color = "Spacing (ft):") +
scale_linetype_manual(values = c(1, 2),
labels = c("Updated","Current")) +
theme_classic() +
theme(plot.title = element_text(hjust = 0.5, margin = margin(45,0,20,0), size = 18),
legend.position="top",
legend.box.background = element_rect(colour = "black", size = 0.5),
legend.box.margin = margin(0,0,0,0), legend.background = element_blank()) +
scale_color_binned(guide = guide_legend(), type = "viridis")
There should be 5 different colors showing but only three are printed in the legend.
Try this:
library(ggplot2)
ggplot(Span_M.E.M, aes(L, colour = S, group = S)) +
geom_line(aes(y = Current, linetype = "Current")) +
geom_line(aes(y = Updated, linetype = "Updated")) +
scale_colour_continuous(guide = guide_legend(), type = "viridis") +
labs(x = element_text("Span Length (ft)"), y = element_blank(),
title = paste("Moment Live Load Distribution Factors \n Exterior Girder - Multi Lane"),
linetype = element_blank(), color = "Spacing (ft):") +
scale_linetype_manual(values = c(1, 2),
labels = c("Updated","Current")) +
theme_classic() +
theme(plot.title = element_text(hjust = 0.5, margin = margin(45,0,20,0), size = 18),
legend.position="top",
legend.box.background = element_rect(colour = "black", size = 0.5),
legend.box.margin = margin(0,0,0,0), legend.background = element_blank())

ggplot pie chart choose axes ticks

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().

R stacked bar graph plotting geom_text

I'm trying to plot a stacked bar graph in R using ggplot. I also want to include percentage in each piece of bars for that piece. I tried to follow the posts 1, 2, 3 but the values are not exactly in their respective blocks. My data is a file in dropbox.
My code is as follows:
f<-read.table("Input.txt", sep="\t", header=TRUE)
ggplot(data=f, aes(x=Form, y=Percentage, fill=Position)) +
geom_bar(stat="identity", colour="black") +
geom_text(position="stack", aes(x=Form, y=Percentage, ymax=Percentage, label=Percentage, hjust=0.5)) +
facet_grid(Sample_name ~ Sample_type, scales="free", space="free") +
opts(title = "Input_profile",
axis.text.x = theme_text(angle = 90, hjust = 1, size = 8, colour = "grey50"),
plot.title = theme_text(face="bold", size=11),
axis.title.x = theme_text(face="bold", size=9),
axis.title.y = theme_text(face="bold", size=9, angle=90),
panel.grid.major = theme_blank(),
panel.grid.minor = theme_blank()) +
scale_fill_hue(c=45, l=80)
ggsave("Output.pdf")
The output is-
Any help is greatly appreciated.
Thank you for your help and time!
I think you're using an older version of ggplot2. Because with your code modified for ggplot2 v 0.9.3, I get this:
p <- ggplot(data = df, aes(x = Form, y = Percentage, fill = Position))
p <- p + geom_bar(stat = "identity", colour = "black")
p <- p + geom_text(position = "stack", aes(x = Form, y = Percentage, ymax = Percentage, label = Percentage, hjust = 0.5))
p <- p + facet_grid(Sample_name ~ Sample_type, scales="free", space="free")
p <- p + theme(plot.title = element_text("Input_profile"),
axis.text.x = element_text(angle = 90, hjust = 1, size = 8, colour = "grey50"),
plot.title = element_text(face="bold", size=11),
axis.title.x = element_text(face="bold", size=9),
axis.title.y = element_text(face="bold", size=9, angle=90),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank())
p <- p + scale_fill_hue(c=45, l=80)
p
You see that the text objects are normally placed properly. There are places where the bars are just too short so that the numbers overlap. You can also play with the size parameter.
To rectify that, you could do something like this to add up the numbers by yourself.
df <- ddply(df, .(Form, Sample_type, Sample_name), transform,
cum.perc = Reduce('+', list(Percentage/2,cumsum(c(0,head(Percentage,-1))))))
p <- ggplot(data = df, aes(x = Form, y = Percentage, fill = Position))
p <- p + geom_bar(stat = "identity", colour = "black")
p <- p + geom_text(aes(x = Form, y = cum.perc, ymax = cum.perc, label = Percentage, hjust = 0.5), size=2.7)
p <- p + facet_grid(Sample_name ~ Sample_type, scales="free", space="free")
p <- p + theme(plot.title = element_text("Input_profile"),
axis.text.x = element_text(angle = 90, hjust = 1, size = 8, colour = "grey50"),
plot.title = element_text(face="bold", size=11),
axis.title.x = element_text(face="bold", size=9),
axis.title.y = element_text(face="bold", size=9, angle=90),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank())
p <- p + scale_fill_hue(c=45, l=80)
p
This gives:
Here a solution using barchart from lattice.
library(latticeExtra)
barchart(Percentage~Form|Sample_type*Sample_name,data=dat,
groups =Position,stack=T,
panel=function(...){
panel.barchart(...)
ll <- list(...)
keep <- !is.na(ll$groups[ll$subscripts])
x <- as.numeric(ll$x[keep])
y <- as.numeric(ll$y[keep])
groups <- as.numeric(factor(ll$groups)[ll$subscripts[keep]])
for (i in unique(x)) {
ok <- x == i
ord <- sort.list(groups[ok])
pos <- y[ok][ord] > 0
nok <- sum(pos, na.rm = TRUE)
h <- y[ok][ord][pos]
panel.text(x = rep(i, nok),y = cumsum(h)-0.5*h,
label = h,cex=1.5)
}
},
auto.key = list(columns = 5),
par.settings = ggplot2like(n = 5),
lattice.options = ggplot2like.opts())

Resources