Related
I want to combine multiple ggplots into one plot with same x and y axis. This is my data. I have one Time column and 6 trend columns (A_Trnd, B_Trnd, C_Trnd etc). I have generated plot for Time vs A_Trnd.
library(ggplot2)
library(scales)
result <- read.csv("Downloads/Questions Trend - Questions Trend.csv")
result$Time_Formatted <- as.Date(result$Time_Formatted)
date_breaks <- as.Date(c("9/1/08", "5/12/14", "7/1/17", "2/2/19", "6/3/20"), "%m/%d/%y")
p1 <- ggplot(result, aes(result$Time_Formatted, result$A_Trnd)) +
geom_point(size = 0.1) + xlab("Month") + ylab("Temporal Trend") +
scale_x_date(breaks = date_breaks , date_labels = "%Y-%m", limits = c(as.Date("2008-08-01"), as.Date("2021-08-01"))) +
theme(axis.text.x = element_text(angle = 70, vjust = 0.9, hjust = 1))
p1 + geom_smooth(method = "loess", color = "red")
Now, I want to plot the same for Time vs B_Trnd, Time vs C_Trnd and have a combine plot like below.
How can I achieve this?
library(tidyverse)
library(scales)
result <-read.csv("Downloads/Questions Trend - Questions Trend.csv") %>%
mutate(Time = as.Date(Time, format = "%m/%d/%y")) %>%
pivot_longer(cols = -Time, names_to = "group", values_to = "value")
date_breaks <- as.Date(c("9/1/08", "5/12/14", "7/1/17", "2/2/19", "6/3/20"), "%m/%d/%y")
p1 <- ggplot(result, aes(Time, value)) +
geom_point(size = 0.1) +
labs(x = "Month", y = "Temporal Trend") +
scale_x_date(breaks = date_breaks , date_labels = "%Y-%m", limits = c(as.Date("2008-08-01"), as.Date("2021-08-01"))) +
theme(axis.text.x = element_text(angle = 70, vjust = 0.9, hjust = 1),
legend.position = "none") +
geom_smooth(method = "loess", aes(color = group)) +
facet_wrap(vars(group), nrow = 1)
p1
This post describes a method to create a two-line x-axis (year below months) on a time series plot. Unfortunately, the method that I use from this post (option 2) is not compatible with ggsave().
library(tidyverse)
library(lubridate)
df <- tibble(
date = as.Date(41000:42000, origin = "1899-12-30"),
value = c(rnorm(500, 5), rnorm(501, 10))
)
p <- ggplot(df, aes(date, value)) +
geom_line() +
geom_vline(
xintercept = as.numeric(df$date[yday(df$date) == 1]), color = "grey60"
) +
scale_x_date(date_labels = "%b", date_breaks = "month", expand = c(0, 0)) +
theme_bw() +
theme(panel.grid.minor.x = element_blank()) +
labs(x = "")
# Get the grob
g <- ggplotGrob(p)
# Get the y axis
index <- which(g$layout$name == "axis-b") # which grob
xaxis <- g$grobs[[index]]
# Get the ticks (labels and marks)
ticks <- xaxis$children[[2]]
# Get the labels
ticksB <- ticks$grobs[[2]]
# Edit x-axis label grob
# Find every index of Jun in the x-axis labels and a year label
junes <- grep("Jun", ticksB$children[[1]]$label)
ticksB$children[[1]]$label[junes] <-
paste0(
ticksB$children[[1]]$label[junes],
"\n ", # adjust the amount of spaces to center the year
unique(year(df$date))
)
# Center the month labels between ticks
ticksB$children[[1]]$label <-
paste0(
paste(rep(" ", 12), collapse = ""), # adjust the integer to center month
ticksB$children[[1]]$label
)
# Put the edited labels back into the plot
ticks$grobs[[2]] <- ticksB
xaxis$children[[2]] <- ticks
g$grobs[[index]] <- xaxis
# Draw the plot
grid.newpage()
grid.draw(g)
# Save the plot
ggsave("plot.png", width = 11, height = 8.5, units = "in")
A plot is saved, but without the years. How do I ggsave() the final plot from grid.draw(g)? This grid.draw(g) plot is shown below, but the actual plot.png file is slightly different, with the three years 2012, 2013 and 2014 omitted.
library(tidyverse)
library(lubridate)
library(scales)
set.seed(123)
df <- tibble(
date = as.Date(41000:42000, origin = "1899-12-30"),
value = c(rnorm(500, 5), rnorm(501, 10))
)
# create year column for facet
df <- df %>%
mutate(year = as.factor(year(date)))
p <- ggplot(df, aes(date, value)) +
geom_line() +
geom_vline(xintercept = as.numeric(df$date[yday(df$date) == 1]), color = "grey60") +
scale_x_date(date_labels = "%b",
breaks = pretty_breaks(),
expand = c(0, 0)) +
# switch the facet strip label to the bottom
facet_grid(.~ year, space = 'free_x', scales = 'free_x', switch = 'x') +
labs(x = "") +
theme_bw(base_size = 14, base_family = 'mono') +
theme(panel.grid.minor.x = element_blank()) +
# remove facet spacing on x-direction
theme(panel.spacing.x = unit(0,"line")) +
# switch the facet strip label to outside
# remove background color
theme(strip.placement = 'outside',
strip.background.x = element_blank())
p
ggsave("plot.png", plot = p,
type = "cairo",
width = 11, height = 8.5, units = "in",
dpi = 150)
Using theme_classic()
p <- ggplot(df, aes(date, value)) +
geom_line() +
geom_vline(xintercept = as.numeric(df$date[yday(df$date) == 1]), color = "grey60") +
scale_x_date(date_labels = "%b",
breaks = pretty_breaks(),
expand = c(0, 0)) +
# switch the facet strip label to the bottom
facet_grid(.~ year, space = 'free_x', scales = 'free_x', switch = 'x') +
labs(x = "") +
theme_classic(base_size = 14, base_family = 'mono') +
theme(panel.grid.minor.x = element_blank()) +
# remove facet spacing on x-direction
theme(panel.spacing.x = unit(0,"line")) +
# switch the facet strip label to outside
# remove background color
theme(strip.placement = 'outside',
strip.background.x = element_blank())
p
Add the top and right most borders
ymax <- ceiling(1.1 * max(df$value, na.rm = TRUE))
xmax <- max(df$date, na.rm = TRUE)
p <- ggplot(df, aes(date, value)) +
geom_line() +
geom_vline(xintercept = as.numeric(df$date[yday(df$date) == 1]), color = "grey60") +
scale_x_date(date_labels = "%b",
breaks = pretty_breaks(),
expand = c(0, 0)) +
# switch the facet strip label to the bottom
facet_grid(.~ year, space = 'free_x', scales = 'free_x', switch = 'x') +
labs(x = "") +
theme_classic(base_size = 14, base_family = 'mono') +
theme(panel.grid.minor.x = element_blank()) +
# remove facet spacing on x-direction
theme(panel.spacing.x = unit(0,"line")) +
# switch the facet strip label to outside
# remove background color
theme(strip.placement = 'outside',
strip.background.x = element_blank()) +
### add top and right most borders
scale_y_continuous(expand = c(0, 0), limits = c(0, ymax)) +
geom_hline(yintercept = ymax) +
geom_vline(xintercept = as.numeric(df$date[df$date == xmax])) +
theme(panel.grid.major = element_line())
p
Created on 2018-10-01 by the reprex package (v0.2.1.9000)
Taken from Tung comments above. Add the following at the end of the code chunk in the op's question.
ggsave(
"plot.png",
plot = g,
type = "cairo",
width = 11,
height = 8.5,
units = "in",
dpi = 150
)
I build this plot:
df_ebf <- df_ebf %>%
map_df(rev)
labels.minor <- c("nie","selten","manchmal", "mehrmals", "oft", "sehr oft", "immerzu")
ggplot(data=df_ebf, aes(x=forcats::fct_inorder(Skalen), y=Werte, group="")) +
geom_line(color = "#003560") +
geom_point(color = "#003560") +
coord_flip() +
labs(x="EBF-Skalen") +
scale_y_continuous(limits = c(0, 6), breaks = c(0,1,2,3,4,5,6), sec.axis = dup_axis(),expand = c(0,0)) +
scale_x_discrete(expand = c(0,0)) +
theme(panel.grid.major.y = element_blank(),panel.grid.minor.x = element_blank(),axis.line.x = element_line(size = 1, colour = "black", linetype=1),axis.title=element_blank())
Now I want to add a second x-axis below the lower x-axis with the labels.minor.
I found this and this when looking for a solution in the forum, but it didn't work for my case.
If your labels.minor are at the exact position of the breaks, you can simply paste together the labels with a newline character. Example below:
library(ggplot2)
df <- data.frame(
x = runif(10, min = 0, max = 6),
y = letters[1:10]
)
labels.minor <- c("nie","selten","manchmal", "mehrmals", "oft", "sehr oft", "immerzu")
ggplot(df, aes(x, y)) +
geom_path(aes(group = -1)) +
geom_point() +
scale_x_continuous(limits = c(0, 6), breaks = 0:6,
labels = paste0(0:6, "\n", labels.minor),
sec.axis = sec_axis(~.x, breaks = 0:6))
Created on 2021-04-10 by the reprex package (v1.0.0)
I have this two data.frames
df1 <-
data.frame(unit = factor(1:20, levels = 20:1),
value = sample(1:10, 20, replace = T))
df2 <-
data.frame(unit =
factor(as.vector(sapply(1:20, FUN = function(x) rep(x, 10))).
levels = 1:20),
time = rep(1:10, 20),
value = sample(1:100, 10*20, replace = T))
Which I want to plot side by side like this:
library(ggplot2)
library(cowplot)
plot_grid(ggplot(df1, aes(x=value,y=unit)) +
geom_bar(stat = 'identity') +
scale_x_continuous(position = "top"),
ggplot(df2, aes(x=time,y=value)) +
geom_line() +
facet_grid(rows = vars(unit), scales = "free_y") +
scale_x_continuous(position = "top") +
theme(axis.text.y = element_text(size=6)),
ncol = 2)
which results in this output
Still, the rows from the two plots, mapping variables from the same unit are not perfectly aligned:
What's the easiest way to align them programmatically (so that it will also work with a different number of units)? The solution doesn't need to involve the cowplot package.
A simple solution to achieve this is by using facets for the bar plot, too. As long as the spacing between the panels is the same in both plots this should ensure that the bars and the line plots for each group are aligned. Try this:
df1 <-
data.frame(unit = factor(1:20, levels = 20:1),
value = sample(1:10, 20, replace = T))
df2 <-
data.frame(unit = factor(as.vector(sapply(1:20, FUN = function(x) rep(x, 10))), levels = 1:20),
time = rep(1:10, 20),
value = sample(1:100, 10*20, replace = T))
library(ggplot2)
library(cowplot)
plot_grid(ggplot(df1, aes(x=value,y=unit)) +
geom_bar(stat = 'identity') +
facet_grid(rows = vars(unit), scales = "free_y") +
scale_x_continuous(position = "top") +
theme(panel.spacing.y = unit(1, "pt"), strip.text = element_blank()),
ggplot(df2, aes(x=time,y=value)) +
geom_line() +
facet_grid(rows = vars(unit), scales = "free_y") +
scale_x_continuous(position = "top") +
theme(axis.text.y = element_text(size=6), panel.spacing.y = unit(1, "pt")),
ncol = 2)
If we look at the way the plots are aligned, it seems clear that to have the bars matching the corresponding facets, we have to get rid of the space at either end of the bars' y axis. We can do this with scale_y_discrete(expand = c(0, 0)). We can also scale the width of the bars so that it is equal to the proportion that each of the facet panels takes up in their allotted viewports. Unfortunately this is somewhat dependent on device dimensions. However, a width of 0.8 or 0.9 will get you pretty close.
plot_grid(ggplot(df1, aes(x=value,y=unit)) +
geom_bar(stat = 'identity', width = 0.8) +
scale_x_continuous(position = "top") +
scale_y_discrete(expand = c(0, 0)),
ggplot(df2, aes(x=time,y=value)) +
geom_line() +
facet_grid(rows = vars(unit), scales = "free_y") +
scale_x_continuous(position = "top") +
theme(axis.text.y = element_text(size=6)),
ncol = 2)
This post describes a method to create a two-line x-axis (year below months) on a time series plot. Unfortunately, the method that I use from this post (option 2) is not compatible with ggsave().
library(tidyverse)
library(lubridate)
df <- tibble(
date = as.Date(41000:42000, origin = "1899-12-30"),
value = c(rnorm(500, 5), rnorm(501, 10))
)
p <- ggplot(df, aes(date, value)) +
geom_line() +
geom_vline(
xintercept = as.numeric(df$date[yday(df$date) == 1]), color = "grey60"
) +
scale_x_date(date_labels = "%b", date_breaks = "month", expand = c(0, 0)) +
theme_bw() +
theme(panel.grid.minor.x = element_blank()) +
labs(x = "")
# Get the grob
g <- ggplotGrob(p)
# Get the y axis
index <- which(g$layout$name == "axis-b") # which grob
xaxis <- g$grobs[[index]]
# Get the ticks (labels and marks)
ticks <- xaxis$children[[2]]
# Get the labels
ticksB <- ticks$grobs[[2]]
# Edit x-axis label grob
# Find every index of Jun in the x-axis labels and a year label
junes <- grep("Jun", ticksB$children[[1]]$label)
ticksB$children[[1]]$label[junes] <-
paste0(
ticksB$children[[1]]$label[junes],
"\n ", # adjust the amount of spaces to center the year
unique(year(df$date))
)
# Center the month labels between ticks
ticksB$children[[1]]$label <-
paste0(
paste(rep(" ", 12), collapse = ""), # adjust the integer to center month
ticksB$children[[1]]$label
)
# Put the edited labels back into the plot
ticks$grobs[[2]] <- ticksB
xaxis$children[[2]] <- ticks
g$grobs[[index]] <- xaxis
# Draw the plot
grid.newpage()
grid.draw(g)
# Save the plot
ggsave("plot.png", width = 11, height = 8.5, units = "in")
A plot is saved, but without the years. How do I ggsave() the final plot from grid.draw(g)? This grid.draw(g) plot is shown below, but the actual plot.png file is slightly different, with the three years 2012, 2013 and 2014 omitted.
library(tidyverse)
library(lubridate)
library(scales)
set.seed(123)
df <- tibble(
date = as.Date(41000:42000, origin = "1899-12-30"),
value = c(rnorm(500, 5), rnorm(501, 10))
)
# create year column for facet
df <- df %>%
mutate(year = as.factor(year(date)))
p <- ggplot(df, aes(date, value)) +
geom_line() +
geom_vline(xintercept = as.numeric(df$date[yday(df$date) == 1]), color = "grey60") +
scale_x_date(date_labels = "%b",
breaks = pretty_breaks(),
expand = c(0, 0)) +
# switch the facet strip label to the bottom
facet_grid(.~ year, space = 'free_x', scales = 'free_x', switch = 'x') +
labs(x = "") +
theme_bw(base_size = 14, base_family = 'mono') +
theme(panel.grid.minor.x = element_blank()) +
# remove facet spacing on x-direction
theme(panel.spacing.x = unit(0,"line")) +
# switch the facet strip label to outside
# remove background color
theme(strip.placement = 'outside',
strip.background.x = element_blank())
p
ggsave("plot.png", plot = p,
type = "cairo",
width = 11, height = 8.5, units = "in",
dpi = 150)
Using theme_classic()
p <- ggplot(df, aes(date, value)) +
geom_line() +
geom_vline(xintercept = as.numeric(df$date[yday(df$date) == 1]), color = "grey60") +
scale_x_date(date_labels = "%b",
breaks = pretty_breaks(),
expand = c(0, 0)) +
# switch the facet strip label to the bottom
facet_grid(.~ year, space = 'free_x', scales = 'free_x', switch = 'x') +
labs(x = "") +
theme_classic(base_size = 14, base_family = 'mono') +
theme(panel.grid.minor.x = element_blank()) +
# remove facet spacing on x-direction
theme(panel.spacing.x = unit(0,"line")) +
# switch the facet strip label to outside
# remove background color
theme(strip.placement = 'outside',
strip.background.x = element_blank())
p
Add the top and right most borders
ymax <- ceiling(1.1 * max(df$value, na.rm = TRUE))
xmax <- max(df$date, na.rm = TRUE)
p <- ggplot(df, aes(date, value)) +
geom_line() +
geom_vline(xintercept = as.numeric(df$date[yday(df$date) == 1]), color = "grey60") +
scale_x_date(date_labels = "%b",
breaks = pretty_breaks(),
expand = c(0, 0)) +
# switch the facet strip label to the bottom
facet_grid(.~ year, space = 'free_x', scales = 'free_x', switch = 'x') +
labs(x = "") +
theme_classic(base_size = 14, base_family = 'mono') +
theme(panel.grid.minor.x = element_blank()) +
# remove facet spacing on x-direction
theme(panel.spacing.x = unit(0,"line")) +
# switch the facet strip label to outside
# remove background color
theme(strip.placement = 'outside',
strip.background.x = element_blank()) +
### add top and right most borders
scale_y_continuous(expand = c(0, 0), limits = c(0, ymax)) +
geom_hline(yintercept = ymax) +
geom_vline(xintercept = as.numeric(df$date[df$date == xmax])) +
theme(panel.grid.major = element_line())
p
Created on 2018-10-01 by the reprex package (v0.2.1.9000)
Taken from Tung comments above. Add the following at the end of the code chunk in the op's question.
ggsave(
"plot.png",
plot = g,
type = "cairo",
width = 11,
height = 8.5,
units = "in",
dpi = 150
)