Creating squares with ggplot (what is the height of my y-axis when using categorical variable in y-scale?)
The key to answering OP's question is to fix the aspect ratio of your plot. The images OP shows are all with an aspect ratio that probably matches the direct output of what is in RStudio or the console (default for the particular graphics device OP is using). To fix the issue, you want to either change the width=
and height=
of your graphics output or save file with something like ggsave('filename.png', width=..., height=...)
, or to fix the ratio based on the data.
You can play around with a particular number for width/height and fix the coordinates using coord_fixed()
, but I prefer to do this programmatically to allow for an expansion of any data.
Based on the data OP shared, the ratio should be approximated by the number of observations in the dataset (number of days) and the number of unique values for df$class
. You also may want to tweak some elements of geom_tile()
and control the panel space outside the tiles via scale_*
functions and the expand=
argument.
Heree's the code:
ggplot(df, aes(x=date, y=class, fill=color)) +
geom_tile(height=0.8, width=7) +
scale_fill_identity() +
scale_x_date(expand=expansion(mult=c(0.05))) +
scale_y_discrete(expand=expansion(mult=c(0.7))) +
coord_fixed(ratio = nrow(df)/length(unique(df$class)))
And the output:
You can use ggsave(..., width=... and height=...)
to fix the empty space around the plot if you wish.
Note that I came to select width=
and height=
values for geom_tile()
here more or less by trial-and-error. Height makes sense (since as @teunbrand pointed out, discrete values are separated by ~1 unit). For width, I figured since dates are probably mapped as 1 day = 1 unit and there were 4 in a month here... each block was about 7 days. It seemed to work out well.