Reputation: 9018
How can I make the x-axis display the text in the "xaxisTitles" vector?
Here is my code you can run:
require(ggplot2)
require(reshape)
xaxisTitles<- cbind("a","b","c","d","e","f","g","h","j","k")
df <- data.frame(time = 1:10,
a = cumsum(rnorm(10)),
b = cumsum(rnorm(10)),
c = cumsum(rnorm(10)))
df <- melt(df , id = 'time', variable_name = 'series')
# plot on same grid, each series colored differently --
# good if the series have same scale
ggplot(df, aes(time,value)) + geom_line(aes(colour = series))+ theme(axis.text.x = xaxisTitles)
I am getting the error:
Error in (function (el, elname) :
Element axis.text.x must be a element_text object.
Upvotes: 2
Views: 7981
Reputation: 59355
The reason you are getting the error is that theme(...)
is used to set the appearance of the axis text (e.g., color, font family, font face, size, orientation, etc.), but not the values of the text. To do that, as @SteveReno points out, you have to use scale_x_discrete(...)
.
require(ggplot2)
require(reshape)
set.seed(321)
# xaxisTitles<- cbind("a","b","c","d","e","f","g","h","j","k")
xaxisTItles<- letters[1:10] # easier way to do this...
df <- data.frame(time = 1:10,
a = cumsum(rnorm(10)),
b = cumsum(rnorm(10)),
c = cumsum(rnorm(10)))
df <- melt(df , id = 'time', variable_name = 'series')
# plot on same grid, each series colored differently --
# good if the series have same scale
ggplot(df, aes(time,value)) +
geom_line(aes(colour = series))+
scale_x_discrete(labels=xaxisTitles)+
theme(axis.text.x=element_text(face="bold",colour="red",size=14))
Upvotes: 5
Reputation: 1384
You can just use scale_x_discrete to set the labels.
ggplot(df, aes(time,value)) + geom_line(aes(colour = series))+ scale_x_discrete(labels= xaxisTitles)
Here's some more helpful info http://docs.ggplot2.org/0.9.3.1/scale_discrete.html
Upvotes: 2
Reputation: 78600
The best way to do this is to make the time
variable a factor rather than a numeric vector, as long as you remember to adjust the group
aesthetic:
df$time = factor(xaxisTitles[df$time])
ggplot(df, aes(time, value)) + geom_line(aes(colour = series, group=series))
(If you don't add the group=series
argument, it won't know that you want to connect lines across the factor on the x
axis).
Upvotes: 2