如何反转图例(标签和颜色),使高值从底部开始?

34

如何最佳地反转图例标签顺序,使数字 7 在下方,数字 1 在上方?

ggplot 图例挑战

df$day <- as.numeric(df3$day)
blues <- colorRampPalette(c('#132B43', '#56B1F7'))

p4 <- 
    ggplot(subset(df,feedback==1&stp>20), aes(x=correct, fill=day, colour=day)) +
    geom_histogram(colour="black", binwidth=10) +
    facet_grid(day ~ .) +
    ggtitle("Over-pronation histogram") +
    ylab("Count (150s period)") +
    xlab("% Steps in over-pronation") +guide_legend(reverse = false)

5
你尝试过使用guide_legend(reverse = TRUE)吗? - Harpal
当然尝试过了,但没有效果。 - user1205101
数据集:https://www.dropbox.com/s/5vfjk5kpvfv1vqe/_logs9.csv 代码:https://www.dropbox.com/s/b0ckwshfs3ipq57/_embspaper.R - user1205101
3个回答

57

你的代码很奇怪,使用了 false 而不是 FALSE,并且 guide_legend 的位置放错了。正确的用法是(@Harpal 给出了提示):

ggplot(data.frame(x=1:4, y=4:1, col=factor(1:4)), aes(x=x, y=y, col=col)) + 
  geom_point(size=10)
ggplot(data.frame(x=1:4, y=4:1, col=factor(1:4)), aes(x=x, y=y, col=col)) + 
  geom_point(size=10) + guides(colour = guide_legend(reverse=T))

enter image description here enter image description here


17

如果您将其放置在数字上,并且它是一个连续的比例尺,则最好使用scale_fill_continuous(trans = 'reverse')scale_colour_continuous。使用您的代码,这将给出:

ggplot(subset(df,feedback==1&stp>20), aes(x=correct, fill=day, colour=day)) +
    geom_histogram(colour="black", binwidth=10) +
    facet_grid(day ~ .) +
    ggtitle("Over-pronation histogram") +
    ylab("Count (150s period)") +
    xlab("% Steps in over-pronation")+
    scale_fill_continuous(trans = 'reverse')

8

连续的比例尺需要使用guide_colorbar

这里我反转了颜色方向。然后我用不同的函数反转了颜色和大小顺序

library(tidyverse)
library(janitor)
iris %>% 
  as_tibble() %>% 
  clean_names() %>% 
  ggplot(aes(x = sepal_length,
             y = petal_width,
             size = sepal_width,
             color = petal_length)) +
  geom_point() +
  facet_wrap(~species,scales = "free") +
  #reverse color direction (the higher in value, the darker in color)
  scale_color_continuous(trans = 'reverse') +
  #edit legends
  guides(
    #reverse color order (higher value on top)
    color = guide_colorbar(reverse = TRUE),
    #reverse size order (higher diameter on top) 
    size = guide_legend(reverse = TRUE))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接