I am plotting a simple violin plot that shows violins of a variable for 2 years, so i just need the "2017" and "2018" to appear in the X axis, but more tick marks are appearing, from 2016.5, 2017.0, 2017.5... until 2018.5. In the "year" column in my data i only have the two years that i want to plot. I don't understand why is it showing like this. Here is my code and an image of the graph I am getting!
sum.data <- ddply(df, .(Field), summarize, mean.TF = mean(TF, na.rm = T))
(violin <-
ggplot(df, aes(Year, TF)) +
geom_violin(aes(fill = factor(Year))) +
stat_summary(fun.y=mean, geom ="point", shape=18, size=2) +
labs(x= NULL, y= "Total FAME") +
facet_grid(Field ~.) +
geom_hline(data = sum.data, aes(yintercept = mean.TF), linetype = 3) +
scale_y_continuous(breaks = seq(0,300,50)) +
theme.custom)
This happened because Year
is a numeric variable, and ggplot made that separation based on the values, if you had more years probably that would not happen. Here are two solutions.
df <-
tibble(
x = rep(2014:2015, each = 100),
y = c(rnorm(100),rexp(100))
)
df %>%
ggplot(aes(x,y))+
geom_violin(aes(fill = factor(x)))
That is a nice solution, because also solves the aesthetic fill
, it could complicate some other geometry but that is very specific.
df %>%
mutate(x = as.factor(x)) %>%
ggplot(aes(x,y))+
geom_violin(aes(fill = x))
Using scale you can set whatever labels
or breaks
, but you still need to transform the variable for the aesthetic fill
.
df %>%
ggplot(aes(x,y))+
geom_violin(aes(fill = factor(x)))+
scale_x_continuous(breaks = 2014:2015)