Axis Transformation in ggplot for 3-axis graphs - r

I'm trying to transform my primary axis to make all the data readable in relation to the secondary axis. Here's the code I'm using:
ggplot(data = NOAARainfallAirTemp, aes(x = Date)) +
geom_smooth(aes(y = Temp, color ="Temperature"), method = "loess", span = 0.3, fill = "blue") +
geom_point(aes(y = Temp, color = "Temperature"), alpha = 0.3) +
geom_smooth(aes(y = PRCP*6, color = "Precipitation"), method = "loess", span = 0.3, fill = "orange") +
geom_point(aes(y = PRCP*6, color = "Precipitation"), alpha = 0.3) +
scale_x_date(expand = c(0.001,0.001), date_breaks = "3 months", date_labels = "%b%Y", date_minor_breaks = "1 month") +
scale_y_continuous(expand = c(0.001,0.001), sec.axis = sec_axis(~./6, name = "Precipitation")) +
ylab("Temperature (°C)") +
ggtitle("Diagnostics of NOAA Data") +
theme(axis.text.x=element_text(angle = 90, hjust = 0), plot.title = element_text(hjust = 0.5)) +
guides(shape = guide_legend(override.aes = list(shape = 15)), color = guide_legend(override.aes = list(fill = NA))) +
theme(panel.grid.major = element_blank(), panel.grid.minor = element_line(colour = "grey"),panel.background = element_blank(), axis.line = element_line(colour = "black"))
The code makes this graph:
As you can see, it's hard to make out trends, especially for the precipitation data. Is there a way to "spread out" the data for the primary axis or is there a better way of going about this?
Any help will be greatly appreciated!

Related

how to put legend as a label in the middle of line in ggplot2

here is my data and code for chart line:
df<- data.frame(direct= 10:85, indirect= 55:130, age=15:90)
ggplot(data=df)+
geom_line(mapping=aes(y=direct,x= age,color="direct"),linetype="solid" ) +
geom_line(mapping=aes(y=indirect,x= age,color="indirect"),linetype="dashed") +
scale_color_manual(values = c(
'direct' = 'black',
'indirect' = 'black')) +
labs(color = NULL)+
scale_x_continuous(breaks = seq(15, 90, by = 5))+
labs(y= "Time Spent (in minutes)")+
guides(color = guide_legend(override.aes = list(linetype = c("solid","dashed"))))+
theme_classic()+
theme(plot.title = element_text(hjust = 0.5, size=9, face="bold"),legend.position=c(.90,.90))
I want to put legend in the middle of my each line as the picture:
You can add annotate to your lines. You can use the following code:
library(tidyverse)
df<- data.frame(direct= 10:85, indirect= 55:130, age=15:90)
ggplot(data=df)+
geom_line(mapping=aes(y=direct,x= age,color="direct"),linetype="dashed" ) +
geom_line(mapping=aes(y=indirect,x= age,color="indirect"),linetype="solid") +
scale_color_manual(values = c(
'direct' = 'black',
'indirect' = 'black')) +
labs(color = NULL)+
scale_x_continuous(breaks = seq(15, 90, by = 5))+
labs(y= "Time Spent (in minutes)")+
guides(color = guide_legend(override.aes = list(linetype = c("solid","dashed"))))+
theme_classic()+
theme(plot.title = element_text(hjust = 0.5, size=9, face="bold"), legend.position = "none") +
annotate('text', x=50, y=55, label = "direct")+
annotate('text', x=50, y=100, label = "indirect")
Output:
Not 100% what you desired. But one option would be the geomtextpath package which allows to easily add direct labels to lines or ...
library(ggplot2)
library(geomtextpath)
df <- data.frame(direct = 10:85, indirect = 55:130, age = 15:90)
ggplot(data = df) +
geom_textline(mapping = aes(y = direct, x = age, color = "direct",
label = "direct"), linetype = "solid", offset = unit(5, "pt"), gap = FALSE) +
geom_textline(mapping = aes(y = indirect, x = age, color = "indirect",
label = "indirect"), linetype = "dashed", offset = unit(5, "pt"), gap = FALSE) +
scale_color_manual(values = c(
"direct" = "black",
"indirect" = "black"
)) +
labs(color = NULL) +
scale_x_continuous(breaks = seq(15, 90, by = 5)) +
labs(y = "Time Spent (in minutes)") +
guides(color = guide_legend(override.aes = list(linetype = c("solid", "dashed")))) +
theme_classic() +
theme(plot.title = element_text(hjust = 0.5, size = 9, face = "bold"), legend.position = c(.90, .90)) +
guides(color = "none")

ggplot - R - Alluvial charts - More space between bars

I made to build this chart with ggalluvial but I couldn't manage to put the labels in a proper way that is not overlapping. Does anyone know what I can do to make it better? I was thinking in make the space between the bars wider but I didn't manage to do it.
So far I did this:
ggplot(data = alluvialTransposedNA,
aes(x = x, stratum = stratum, alluvium = id,
y = Freq, fill = Agency, label = stratum)) +
scale_x_discrete(expand = c(.1, .1)) +
scale_y_continuous(expand = c(.2, .2)) +
geom_alluvium(aes(fill = Agency), width = 1/6) +
geom_stratum(width = 1/3, alpha = 1.5) + +
geom_label(stat = "stratum", aes(label = after_stat(stratum)),size=2) +
theme(legend.position = "bottom",
axis.text.x = element_text(angle = 45, vjust = 0.75, hjust=1),
axis.title.x = element_blank(),
axis.title.y = element_blank(),
axis.ticks = element_blank(),
plot.title = element_text(hjust = 0.5)) +
guides(fill=guide_legend(override.aes = list(color=mycolors[1:2])))+
ggtitle("Evolution topics during covid-19")

How to draw three differents non-linear regression with ggplot2

I am trying to draw three differents non-linear regression with ggplot2 (like I did with graphpad below (dotted line) (because graphpad can't compare non-linear regression between groups):
So far, I drew this graph:
With the following code:
gp <- ggplot(datapoidsmono, aes(x = time, y = weight)) +
stat_summary(aes(color = group), fun.data="mean_sdl", fun.args = list(mult=1), geom="errorbar", position = "identity", size=0.5, width=0.2) +
stat_summary(fun.y = "mean", geom = "point", size=3, aes(shape=group,color=group)) +
scale_x_discrete(name = "Days after injection") +
scale_y_continuous(name = "Weight (g)", limits=c(0, 4000), breaks = seq(0, 4000,500)) +
scale_color_manual(values=c("green", "blue", "red"), name="Treatment", labels=c("A","B","C")) +
scale_shape_manual(values=c(15,16,17), name ="Treatment", labels=c("A", "B", "C")) +
ggtitle("Weight variation over time") + theme(plot.title = element_text(hjust = 0.5)) +
theme(legend.position = "right") +
theme(legend.background = element_rect(size=0.5, linetype="solid", color ="black", fill="white")) +
theme(axis.line.x = element_line(size = 0.5, color = "black"),axis.text.x = element_text(color="black", size = 12),axis.line.y = element_line(size = 0.5, color = "black"),axis.text.y = element_text(color="black", size = 12),axis.title = element_text(size =15, face="bold"),plot.title = element_text(size =20, face = "bold"),panel.grid.major = element_line(color = "#F1F1F1"),panel.grid.minor = element_blank(), panel.background = element_blank())
I can't figure out how to draw a non-linear regression for each groups.
The following code did not return any drawn line (no error either):
ggplot(datapoidsmono, aes(time, weight, color = group)) +
geom_point() +
stat_smooth(method = "lm", se=FALSE)
Nor did this one (found here):
ggplot(datapoidsmono, aes(x = time, y = weight, colour=group)) +
stat_smooth(method = 'nls', formula = 'y~a*exp(b*x)') +
stat_smooth(color = 1, method = 'nls', formula = 'y~a*exp(b*x)') +
geom_point(aes(fill=group))
Any idea or clue would be useful to continue! Thanks
Update
As suggested by #PoGibas, I added "group=group" in aes inside first line which worked pefectly to draw the lines!
I tried mulltiple solution to get the perfect fit:
gp + ggplot(aes(group=group))
stat_smooth(method = "lm", formula = y ~ x, size = 1, se = FALSE,colour = "black") +
stat_smooth(method = "lm", formula = y ~ x + I(x^2),size = 1, se = FALSE, colour = "blue") +
stat_smooth(method = "loess", formula = y ~ x, size = 1, se = FALSE, colour = "red") +
stat_smooth(method = "gam", formula = y ~ s(x), size = 1, se = FALSE, colour = "green") +
stat_smooth(method = "gam", formula = y ~ s(x, k = 3), size = 1, se = FALSE, colour = "violet") +
stat_smooth(method = "auto", se=F, colour = "yellow")
But I figured that simply gp + stat_smooth() did perfectly the job (the LOESS method is used).
Now I am trying to change aspect (to a dotted line) and color of the fit...
I tryed gp + stat_smooth(se=F, aes(fill = group)) but now I have another legend box and my lines are always with the same color...
I also tryed to add linetype=group in the aes, but when I use scale_linetype_manual(values=c("dotted", "dotted", "dotted")), every line is dotted (included errorbar)
The complete code is:
ggplot(datapoidsmono, aes(x = time, y = weight, group=group, linetype=group)) +
stat_summary(aes(color = group), fun.data="mean_sdl", fun.args = list(mult=1), geom="errorbar", position = "identity", size=0.5, width=0.2) +
stat_summary(fun.y = "mean", geom = "point", size=3, aes(shape=group,color=group)) +
scale_x_discrete(name = "Days after injection") +
scale_y_continuous(name = "Weight (g)", limits=c(0, 4000), breaks = seq(0, 4000,500)) +
scale_color_manual(values=c("green", "blue", "red"), name="Treatment", labels=c("A","B","C")) +
scale_shape_manual(values=c(15,16,17), name ="Treatment", labels=c("A", "B", "C")) +
ggtitle("Weight variation over time") + theme(plot.title = element_text(hjust = 0.5)) +
theme(legend.position = "right") +
theme(legend.background = element_rect(size=0.5, linetype="solid", color ="black", fill="white")) +
theme(axis.line.x = element_line(size = 0.5, color = "black"),axis.text.x = element_text(color="black", size = 12),axis.line.y = element_line(size = 0.5, color = "black"),axis.text.y = element_text(color="black", size = 12),axis.title = element_text(size =15, face="bold"),plot.title = element_text(size =20, face = "bold"),panel.grid.major = element_line(color = "#F1F1F1"),panel.grid.minor = element_blank(), panel.background = element_blank()) +
stat_smooth(se=F, aes(fill = group)) +
scale_linetype_manual(values=c("dotted", "dotted", "dotted"))
Thanks to #PoGibas and this post, I added
group=group, color=group in the aes of ggplot and it gave me a good result.
ggplot(datapoidsmono, aes(x = time, y = weight, group=group, color=group)) +
stat_summary(aes(color = group), fun.data="mean_sdl", fun.args = list(mult=1), geom="errorbar", position = "identity", size=0.5, width=0.2) +
stat_summary(fun.y = "mean", geom = "point", size=3, aes(shape=group,color=group)) +
scale_x_discrete(name = "Days after injection") +
scale_y_continuous(name = "Weight (g)", limits=c(0, 4000), breaks = seq(0, 4000,500)) +
scale_color_manual(values=c("green", "blue", "red"), name="Treatment", labels=c("A","B","C")) +
scale_shape_manual(values=c(15,16,17), name ="Treatment", labels=c("A", "B", "C")) +
ggtitle("Weight variation over time") + theme(plot.title = element_text(hjust = 0.5)) +
theme(legend.position = "right") +
theme(legend.background = element_rect(size=0.5, linetype="solid", color ="black", fill="white")) +
theme(axis.line.x = element_line(size = 0.5, color = "black"),axis.text.x = element_text(color="black", size = 12),axis.line.y = element_line(size = 0.5, color = "black"),axis.text.y = element_text(color="black", size = 12),axis.title = element_text(size =15, face="bold"),plot.title = element_text(size =20, face = "bold"),panel.grid.major = element_line(color = "#F1F1F1"),panel.grid.minor = element_blank(), panel.background = element_blank()) +
stat_smooth(se=F, linetype="dotted")
Here is the final graph:
NB: the fit proposed by graphpad (see first graph) is more stat_smooth(method = "lm", formula = y ~ x + I(x^2),size = 1, se = FALSE) than the one I finally chose (LOESS)

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

unable changing linetype ggplot2

I would like to change color and line type in my ggplot. I am using this code:
a <- runif(84, 20, 80)
a<-ts(a,start = 2009,frequency = 12)
#a<-ts(result$`dataset1$Summe`,start = 2009,frequency = 12)
a3 <- zoo(a, order.by = as.Date(yearmon(index(a))))
p1 <- autoplot(a3)
p1 + scale_x_date(labels = date_format("%m/%Y"),breaks = date_breaks("2 months"), limits = as.Date(c('2009-01-01','2017-08-01')))+ theme(axis.text.x = element_text(angle = 90))+ theme(axis.text.x = element_text(angle = 90))+
labs(x = "Date",y="Test") + theme(panel.background = element_rect(fill = 'white', colour = 'black'))+geom_line(linetype="dotted", color="red")
but only the color is changed. What should I do to change line type?
autoplot() will pick a sensible default for the object it's passed. If you want to customize its appearance it's probably better to use the standard ggplot() function.
To be able to do that the zoo object should be passed trough fortify():
ggplot(fortify(a3, melt = TRUE)) +
geom_line(aes(x = Index, y = Value), linetype='dashed', color="red") +
scale_x_date(labels = date_format("%m/%Y"),
breaks = date_breaks("2 months"),
limits = as.Date(c('2009-01-01','2017-08-01')))+
theme(axis.text.x = element_text(angle = 90),
axis.text.x = element_text(angle = 90),
panel.background = element_rect(fill = 'white', colour = 'black'))+
labs(x = "Date",y="Test")
(NB: the dashed line at the top is caused by the panel.background theme option)

Resources