问题
I am using ggplot and facet_wrap to get the required plots. I have to add few things to the labels of each facet or the variable or the name of each facet, just like how we modify the xlab and ylab directly under ggplot.
Example:
d <- ggplot(diamonds, aes(carat, price, fill = ..density..)) +
xlim(0, 2) + stat_binhex(na.rm = TRUE) + theme(aspect.ratio = 1)
d + facet_wrap(~ color)
All I want to do now is to change the label of each facet i,e D,E,F,G,H,I,J to something else.
How can I modify this?
Addition
Sorry I tried to break it but, it take time so I have added it in github. You can upload the file and check the result. The problem is with the option 4 facet_wrap...you can select the radio button option 4.
I have commented the previous facet_wrap I was using where the data integrity is fine, but if I change the facet wrap, the graph behaves differently and also the data.
Data to upload can be found in the folder "Data to upload"
Code can be found here: I will add this in a minute
回答1:
Based on what I know, facet_grid
might be a better solution in this case. facet_grid
can not only help you group plots by one variable, but also two or even more, there is an argument called labeller
which is designed to customize the label.
myfunction <- function(var, string) {
print(var)
print(string)
result <- paste(as.character(string),'_new', sep="")
return(result)
}
ggplot(diamonds, aes(carat, price, fill = ..density..)) + xlim(0, 2) +
stat_binhex(na.rm = TRUE) + theme(aspect.ratio = 1) + facet_grid(~color, labeller=myfunction, as.table=TRUE)
# OUTPUT
[1] "color"
[1] D E F G H I J
Levels: D < E < F < G < H < I < J
However, as you can see, the plot is in one row and I don't think it can be easily broken into multiple rows even if you turned on the as.table
flag based on here.
Do you think it will be feasible if you add a new column dedicated for labelling? Then you can keep the awesomeness of facet_wrap
...
diamonds$label <- paste(as.character(diamonds$color), "_new", sep="")
ggplot(diamonds, aes(carat, price, fill = ..density..)) + xlim(0, 2) +
stat_binhex(na.rm = TRUE) + theme(aspect.ratio = 1) + facet_wrap(~label)
回答2:
Though its a very old question , i would like to answer it for i learnt one easy method!!
This solution is with facet_wrap() and without changing your data in any manner also.
text.on.each.panel <-"_new"
d <- ggplot(diamonds, aes(carat, price)) +
xlim(0, 2)
d + facet_wrap(~ color, labeller = label_bquote(.(color)-.(text.on.each.panel)))
来源:https://stackoverflow.com/questions/27030179/how-to-change-the-facet-labels-in-facet-wrap