如何解决如何在facet_wrap中更改面板的顺序和标签?
伙计们
我很尴尬地提出建议,以寻求看起来很容易的事情,但是我的挫败感超过了我的尴尬。如何在facet_wrap
中更改单个面板的顺序,标签和线条颜色,同时对其他面板使用自动排序,标记和着色。具体来说,我想为Freedonia及其四个州(Chico,Groucho,Harpo和Zeppo,以Freedonia的创建者之名命名)绘制“布朗克斯欢呼价”,但将Freedonia列为Freedonia的第一个面板图形并将其线变为黑色。这就是我所拥有的:
我(公认的不雅之举)的解决方案是
- 将“ Freedonia”重新编码为“ aaa”(因此它首先出现)。
- 使用
geom_line
语句将数据子集为“ aaa”,并将行颜色更改为黑色。 - 将面板的标签更改回“ Freedonia”。在进入第三步之前,我很好。
以下是一些具有可重现(或可复制)代码的示例:
library(dplyr)
library(ggplot2)
library(data.table)
#Simulate Data
set.seed(581)
state <- rep(c("Chico","Groucho","Harpo","Freedonia","Zeppo"),each=4)
x <- rep(1:4,times = 5)
y <- 100 + rnorm(20,5)*x + rnorm(20,20)
df <- cbind(state,x,y) %>% data.table() %>%
.[,.(state,x = as.numeric(x),y = as.numeric(y))]
#Recode
df <- df[,state := recode(state,"Freedonia" = "aaa")]
#Generate Labels
labels <- unique(df$state[which(state != "Freedonia")])
labels <- c("Freedonia",labels)
#Grid Plot with Freedonia First
p <- ggplot(df,aes(x,y,color = state)) +
geom_line() +
geom_line(data = subset(df,state == "aaa"),color = "black") +
ggtitle("Average bronx Cheers by Quarter (1934)") +
theme_bw() +
theme(legend.position = "none") +
theme(plot.title = element_text(hjust = 0.5)) +
xlab("Quarter") +
ylab("bronx Cheer Rate") +
#facet_wrap(~ state)
#facet_wrap(~ state,labeller = labeller(state = labels))
facet_wrap(~ state,labeller = labeller(setNames(nm = labels)))
p
这是结果。
我认识到只有五个小组,手动进行此操作(例如,scale_fill_manual
是微不足道的),但是您可能已经推测我对Freedonia并不是很感兴趣,但是,在一个县很多的州-太多的手工要做。我看的不是很详尽,而是彻底的,还没有发现任何能解决这个确切问题的东西。
非常感谢您的帮助。
关于, 大卫
解决方法
您可以通过以下方式设置state
的因子级别:'Freedonia'
是第一级别,而其余的级别稍后出现。
library(ggplot2)
df$state <- factor(df$state,levels = c('Freedonia',setdiff(unique(df$state),'Freedonia')))
ggplot(df,aes(x,y,color = state)) +
geom_line() +
geom_line(data = subset(df,state == "Freedonia"),color = "black") +
ggtitle("Average Bronx Cheers by Quarter (1934)") +
theme_bw() +
theme(legend.position = "none") +
theme(plot.title = element_text(hjust = 0.5)) +
xlab("Quarter") +
ylab("Bronx Cheer Rate") +
facet_wrap(~ state)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。