避免在ggplot2中按字母顺序重新排序图例

时间:2018-05-16 12:55:53

标签: r ggplot2 graph

我制作了以下代码,它读取一个表(包含10列)并生成一个折线图。问题是,它按字母顺序重新排序图例。如何避免重新排序并保持原始排序?我已经阅读了如何通过删除breaks来避免它,但我无法解决它。

任何想法都会很棒。

欣赏!

qw是一个数据框。

qw %>% 
  add_rownames() %>% 
  gather(reading, value, -rowname) %>% 
  group_by(rowname) %>% 
  mutate(x=1:n()) %>% 
  ggplot(aes(x=x, y=value, group=rowname)) +
  geom_line(aes(color=rowname), line = 2.5, cex = 1.05) + 
  labs(colour= "Methods",x="XXXX", y="YYYY") + 
  theme(axis.text=element_text(size=14), 
        axis.title=element_text(size=14)) + 
  xlim(min=1, max=10)+ 
  scale_x_continuous(breaks=c(1,2,3,4,5,6,7,8,9,10)) + 
  theme(legend.text=element_text(size=12)) + 
  geom_point() 

1 个答案:

答案 0 :(得分:0)

希望这有助于......

library(tidyverse)

# built-in data is nice for SO and I don't have 'qw'
data("ChickWeight") 
cw <- ChickWeight

# make a new character column 'cw$diet_name', similar to 'qw$rownames'
dc <- LETTERS[1:4] %>% set_names(1:4)
cw$diet_name <- dc[cw$Diet] %>%
    factor(levels = c("C", "B", "D", "A")) # set legend order with levels

ggplot(cw, aes(Time, weight, color = diet_name, group = Chick)) +
    geom_line() # colors are in custom order!

enter image description here

如果不清楚,请告诉我:)