I am trying to customize a plot for this data.
x <- 1:12
z1 <- c("m", "m", "m", "m", "m", "n", "n", "n", "n", "n", "n", "n")
z2 <- c("m", "m", "m", "m", "p", "p", "p", "p", "n", "n", "n", "n")
z3 <- c("m", "m", "m", "p", "p", "p", "n", "n", "n", "n", "n", "n")
So I created a data frame and plotted it.
df <- data.frame(x, z1, z2, z3)
colors <- c("m" = "#f8766d", "n" = "#00BA38", "p" = "#619CFF")
df_long <- pivot_longer(df, cols = c("z1", "z2", "z3"), names_to = "variable", values_to = "value")
df_long$value <- factor(df_long$value, levels = c("m", "n", "p"))
ggplot(df_long, aes(x = variable, fill = value)) +
geom_bar(position = position_stack(reverse = TRUE)) +
coord_flip()
The output is not bad; it looks like this.
But we would like to have three ticks on the x-axis as Jan
, Feb
, Mar
. So Jan
would be where x=1
, then Feb
would be where x=5
and Mar
would be where x=9
.
On the y-axis, we would like to have z(t,1)
, z(t,2)
, z(t,3)
but in italic like what we do with expression()
in labels.
Is it possible to do these? Could someone help please?
Starting from your plot object p
you can change and customize tick marks and labels.
As you mentioned Jan
is placed where x=1
(1 occurrence of m, n or p ,Feb is placed at 5 occurrence)
p=ggplot(df_long, aes(x = variable, fill = value)) +
geom_bar(position = position_stack(reverse = TRUE)) +
coord_flip()
p + theme(axis.text.y = element_text(face="italic")) +
scale_x_discrete(breaks=c("z1","z2","z3"),
labels=c("z(t,1)", "z(t,2)", "z(t,3)"))+
scale_y_continuous(breaks=c(1,5,9),
labels=c("Jan", "Feb", "Mar"))
Created on 2023-04-03 with reprex v2.0.2