 # how to plot two sets of variables as x

Hi all,

I am wondering how to plot two sets of variables as x. This is a picture that I'd like to plot. In this pic, (1) time (EModE and LModE) and genre (Diaries and Journals) are plotted. (2) Diaries and Journals are with different colors. With facet_wrap(), I can plot a similar one, with the four columns in two diagrams and the color for all columns are the same (red and blue).

Here is a test dataset and my code:

``````test
# A tibble: 10 x 4
date gender genre   group
<dbl> <chr>  <chr>   <chr>
1  1778 female diary   s
2  1778 female journal of
3  1778 male   diary   s
4  1778 male   diary   of
5  1778 male   journal s
6  1782 female diary   of
7  1782 female diary   s
8  1782 female journal of
9  1782 female journal s
10  1782 male   journal of

ggplot(test) +
geom_bar(mapping = aes(x = genre, fill = group, color = group), position = "fill") +
facet_wrap(~ date, scales = "free_x") +
labs(x = "Date", y = "Count") +
theme_bw() +
theme(legend.justification = c(1, 0))
``````

Looking forwards to your ideas! Thank you!

Hi!

To help us help you, could you please prepare a reproducible example (reprex) illustrating your issue? Please have a look at this guide, to see how to create one:

Hi!

Here is a start, cribbed from here.. There may well be an easier way.

``````library(ggplot2)
ggplot(test) +
geom_bar(mapping = aes(x = interaction(date,genre, lex.order = TRUE), fill = group, color = group),
position = "fill") +
geom_segment(mapping = aes(x=x,y=y, xend=xend, yend= yend),
data = data.frame(x=2.5, xend=2.5, y =0, yend = -0.2)) +
labs(y = "Count") +
theme_bw() +
theme(legend.justification = c(1, 0),
plot.margin = unit(c(1, 1, 4, 1), "lines"),
axis.title.x = element_blank(),
axis.text.x = element_blank(),
panel.grid.major.x = element_blank(),
panel.grid.minor.x = element_blank()) +
annotate(geom = "text", x = 1:4, y = -0.05, label = c("diary", "journal", "diary", "journal"), size = 4) +
annotate(geom = "text", x = c(1.5, 3.5), y = -0.15, label = c("1778", "1782"), size = 6) +
coord_cartesian(ylim = c(-0.2, 1.1), expand = FALSE, clip = "off")
`````` Created on 2021-01-25 by the reprex package (v0.2.1)

Hi!

Thank you so much for your help!

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.