How do I display the factor ID on the axis of the graph and the factor ID and value in the legend?
I have a graph where request
is a factor with long values, so they are not plotted on the char axis.
plot( time_taken ~ request )
The data in this case looks like this:
time_taken request
1 7 /servlet1/endpoint2/
2 2 /session/
3 10 /servlet1/endpoint3/
4 2 /servlet1/endpoint2/
5 8 /servlet4/endpoint2/
6 5 /session/
...
Question: Is there a way to draw something like the factor level id on the x-axis, and the factor factor id + the full line factor in the legend?
source to share
The code in your question generates a box, so I assume that's what you want. Here are four ways to do it.
This will create a box with a numbered x-axis and full names in the legend.
library(ggplot2)
ggplot(df) +
geom_boxplot(aes(x=as.integer(request),y=time_taken, color=request))+
labs(x="request")
As you can see below, with ggplot the labels are distinguishable (at least in the example).
ggp <- ggplot(df) + geom_boxplot(aes(x=request,y=time_taken))
ggp
In such a situation, I would tend to rotate the plot.
ggp + coord_flip()
Finally, here is the path in the R base, although IMO this is the least attractive option.
plot(time_taken~factor(as.integer(request)),df, xlab="request")
labs <- with(df,paste(as.integer(sort(unique(request))),sort(unique(request)),sep=" - "))
legend("topright",legend=labs)
source to share
A possible solution uses ggplot2
. Following a lead with some sample data.
df <- data.frame(factor = c("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
"ccccccccccccccccccccccccccccccccccccc"),
time = c(5, 7, 9))
library(ggplot2)
qplot(data = df, factor, time) + scale_x_discrete(labels = abbreviate)
You can also use the function directly abbreviate
on your factor levels in your dataframe so you can work with shortcut shortcuts and also avoid ggplot2
if you are not familiar with it. Take a look?abbreviate
source to share