将反向选项添加到R因子函数或ggplot函数

时间:2019-01-29 22:02:10

标签: r ggplot2

我正在尝试对ggplot绘图进行排序,然后归结为未按所需方式排序的数据框。因此,我需要做的就是简单地反转数据框的顺序,该行已按以下顺序用一个因素进行了排序:

df$name <- factor(df$name , levels = unique(df$name))

我尝试通过在以下类似位置添加rev来对其进行修改,但数据框始终出现在RStudio中,并且在我的绘图中的顺序与以前相同

df$name <- factor(df$name , levels = rev(unique(df$name)))
df$name <- factor(df$name , levels = rev(levels(unique(df$name))

实际上,我实际上不需要那里的unique(),所以我删除了它,但是没有看到任何变化。这个语法正确吗?

或者如果要通过ggplot函数对订单进行重新排序,该如何编辑以反转y轴?我尝试添加scale_y_reverse,但由于似乎已经有了scale_y_discrete选项而无法添加,并且在此处将其添加到unused argument (trans = "reverse")选项中时遇到了错误scale_y_discrete

features_plop <-  ggplot(df, aes(y=name, x=data_2018)) + 
  geom_vline(xintercept = 3, size = 0.5, color = "#00C4F3") + #Benchmark static line
  geom_text(data=data.frame(x=2.5,y=2.4), aes(x, y), 
            label="Benchmark", hjust=-1, vjust=-1, colour="#4c4c4c") +
  geom_point(aes(x = pilot), color="#FD5B14", fill="#FD5B14", size=4, pch=3) + 
  geom_point(aes(x = all), color="#2B85BA", fill="#2B85BA", size=4, pch=3) +
  geom_point(aes(x = general), color="#5B15BA", fill="#5B15BA", size=4, pch=3) +
  geom_point(aes(x = data_2017), color="#BCA8DC", fill="#BCA8DC", size=4, pch=16) + 
  geom_point(color="#612CB5", fill="#612CB5", size=4, pch=16) + 
  ylab("Features") + 
  scale_y_discrete(labels = function(mean_2018) str_wrap(mean_2018, width = 60)) +
  scale_x_continuous(sec.axis = dup_axis(), lim = c(1, 4)) + 
  theme_bw() + 
  theme(legend.text = element_text(colour="black", size = 8),
        legend.position="middle",
        axis.title.x =element_blank(),
        axis.text.x = element_blank(),
        axis.ticks.x = element_blank(),
        #axis.line.x.top = element_blank(),
        #axis.text.x.top = element_text(size=8),
        axis.title.y = element_text(angle = 0, vjust = 0.5),
        panel.grid.minor.x = element_line(colour = "#cccccc",
                                          linetype = "solid"),
        panel.grid.major.x = element_line(colour = "#b2b2b2",
                                          linetype = "solid"),
        panel.grid.major.y = element_line(colour = "#7f7f7f",
                                          linetype = "solid"),
        panel.border = element_blank()
  )

0 个答案:

没有答案