简体   繁体   English

ggplot R 中的图例和 x 轴排序问题

[英]Question with Legend and Ordering x-axis in ggplot R

I am having two frustrating problems (fairly new to r!).我有两个令人沮丧的问题(对 r 来说相当陌生!)。

  1. I am trying to order the x axis by Feature, based on the order in my df.我正在尝试根据我的 df 中的顺序按功能对 x 轴进行排序。 When I use scale_shape_manual(labels = c("196", "176", "194")), the graph gets very wonky.当我使用 scale_shape_manual(labels = c("196", "176", "194")) 时,图表变得非常不稳定。

  2. I am trying to fix my legend.我正在尝试修复我的传奇。 I would like for it to list "196", "176", "194" in order rather than 15, 16, 17. When I use scale_fill_manual I get the error message: Warning message: guides(<scale> = FALSE) is deprecated.我希望它按顺序列出“196”、“176”、“194”而不是 15、16、17。当我使用 scale_fill_manual 时,我收到错误消息:警告消息: guides(<scale> = FALSE)是已弃用。 Please use guides(<scale> = "none") instead.请改用guides(<scale> = "none") I don't know of another way to manually change text in legends.我不知道手动更改图例中文本的另一种方法。

df <- data.frame(Feature = c(196, 176, 194),
                 NISP = c(65.26548673, 64.09090909, 72.16494845),
                     Bio = c(18.53298346,   10.68950428,    54.19047619),
                     MNI = c(30, 35, 58))
               
library(ggplot2)
 

Graph <- ggplot(df, aes(x=Feature)) +
  geom_line(aes(y = NISP), color = "black") + 
  geom_line(aes(y = MNI), color = "black") +
  geom_line(aes(y = Bio), color = "black")+
  geom_point(aes(y = NISP, shape="16", size=2))+
  geom_point(aes(y = MNI, shape="15", size=2))+
  geom_point(aes(y = Bio, shape="17", size=2)) +
  ylab("Percentage") + ggtitle("Percent MNI, NISP, and Biomass") + 
  guides(color = FALSE, size = FALSE)

Graph  

ggplot2 works best with data in "long" form, while you're having some issues because your data is in the "wide" format. ggplot2最适用于“长”格式的数据,而您遇到一些问题,因为您的数据是“宽”格式。 Things get easier if we use tidyr to switch to a long format, and I believe it resolves the issues you're having:如果我们使用tidyr切换到长格式,事情会变得更容易,我相信它可以解决您遇到的问题:

df <- data.frame(Feature = c(196, 176, 194),
                 NISP = c(65.26548673, 64.09090909, 72.16494845),
                 Bio = c(18.53298346,   10.68950428,    54.19047619),
                 MNI = c(30, 35, 58))

library(ggplot2)
library(tidyr)
library(dplyr)

df %>%
  pivot_longer(cols = -Feature) %>%
  mutate(Feature=factor(Feature, levels=unique(Feature))) %>%
  ggplot(aes(x=Feature, y=value)) +
  geom_line(aes(group=name)) +
  geom_point(aes(shape=name), size=2) +
  scale_shape_manual(values = c(16, 15, 17)) +
  ylab("Percentage") + ggtitle("Percent MNI, NISP, and Biomass")

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM