Reputation: 2827
I have a data set that looks like this:
df <- data.frame(
EventMonth = c('2015-01', '2015-02', '2015-03', '2015-04', '2015-05', '2015-06', '2015-07', '2015-08', '2015-09', '2015-10', '2015-11', '2015-12',
'2016-01', '2016-02', '2016-03', '2016-04', '2016-05', '2016-06', '2016-07', '2016-08', '2016-09', '2016-10', '2016-11', '2016-12'),
EventQuarter = c('2015-Q1', '2015-Q1', '2015-Q1', '2015-Q2', '2015-Q2', '2015-Q2', '2015-Q3', '2015-Q3', '2015-Q3', '2015-Q4', '2015-Q4', '2015-Q4',
'2016-Q1', '2016-Q1', '2016-Q1', '2016-Q2', '2016-Q2', '2016-Q2', '2016-Q3', '2016-Q3', '2016-Q3', '2016-Q4', '2016-Q4', '2016-Q4'),
score = c(2.59, 2.58, 2.82, 2.60, 2.69, 2.76, 2.68, 2.65, 2.58, 2.51, 2.90, 2.50, 2.65, 2.87, 2.48, 2.59, 2.83, 2.63, 2.73, 2.41, 2.63, 2.60, 2.64, 2.51),
stringsAsFactors = F
)
I am using a command like below to show line graph:
ggplot(df, aes(EventMonth, score)) +
geom_line(stat='identity', group = 1) +
theme_few() + ylim(0, survey[item == col, max.val]) +
ylab(survey[item == col, title]) +
theme(axis.text.x = element_text(angle=90)) +
stat_smooth(aes(as.integer(as.factor(EventMonth)), score), method='loess')
This works beautifully, but there are too many tick marks on the X axis. I would like to instead show only one tick mark per quarter.
As a starting point, I tried adding this to the command, to just show some arbitrary values for each quarter:
+ scale_x_discrete('Event Quarter', c(2, 5, 8, 11), c('a', 'b', 'c', 'd')
But this just makes the entire x-axis ticks and labels disappear, without showing a, b, c, d in places that I expect to see them. What am I doing wrong?
Also, my x axis is an integer axis, so I tried using scale_x_continuous too but couldn't get that to work either. It complained about me supplying discrete values for a continuous scale: scale_x_continuous('Event Quarter', c(2, 5, 8, 11), c('a', 'b', 'c', 'd'))
Upvotes: 4
Views: 4520
Reputation: 2827
The answer is that the value for breaks
in the scale_x_discrete
function is not an integer, but a mapping to the string values.
Essentially, even though in my data df$EventMonth
is of type character
, ggplot will convert it to a factor to display it. While you would think that using values like 1, 2, 3, ... to reference the x-axis should work (after all, a factor is a numeric
type with some labels), it does not work here; instead, if you pass the character values (i.e. the levels of that factor) in the parameter for breaks
it will work.
Here is the working code:
ggplot(df, aes(EventMonth, score)) +
geom_line(stat='identity', group = 1) +
theme_few() + ylim(0, survey[item == col, max.val]) +
ylab(survey[item == col, title]) +
theme(axis.text.x = element_text(angle=90)) +
stat_smooth(aes(as.integer(as.factor(EventMonth)), score), method='loess') +
scale_x_discrete('Event Quarter',
c('2015-02', '2015-05', '2015-08', '2015-11'),
c('2015-Q1', '2015-Q2', '2015-Q3', '2015-Q4'))
Upvotes: 1