首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ggridges的R编码

ggridges的R编码
EN

Stack Overflow用户
提问于 2018-01-26 08:23:26
回答 1查看 968关注 0票数 0

我是用R编码的新手,所以请原谅这个简单的问题。我正在尝试在R中运行ggridges geom来创建月度密度图。代码如下,但它创建了一个按错误顺序排列的月份图:

代码引用了一个包含3列(见下图)的csv数据文件- MST、Aeco_5a和month:

任何关于如何解决这个问题的建议都将不胜感激。下面是我的代码:

代码语言:javascript
复制
> library(ggridges)
> read_csv("C:/Users/Calvin Johnson/Desktop/Aeco_Price_2017.csv")
Parsed with column specification:
cols(
  MST = col_character(),
  Month = col_character(),
  Aeco_5a = col_double()
)
# A tibble: 365 x 3
         MST   Month Aeco_5a
       <chr>   <chr>   <dbl>
 1  1/1/2017 January  3.2678
 2  1/2/2017 January  3.2678
 3  1/3/2017 January  3.0570
 4  1/4/2017 January  2.7811
 5  1/5/2017 January  2.6354
 6  1/6/2017 January  2.7483
 7  1/7/2017 January  2.7483
 8  1/8/2017 January  2.7483
 9  1/9/2017 January  2.5905
10 1/10/2017 January  2.6902
# ... with 355 more rows
> 
> mins<-min(Aeco_Price_2017$Aeco_5a)
> maxs<-max(Aeco_Price_2017$Aeco_5a)
> 
> ggplot(Aeco_Price_2017,aes(x = Aeco_5a,y=Month,height=..density..))+
+     geom_density_ridges(scale=3) +
+     scale_x_continuous(limits = c(mins,maxs)) 
EN

回答 1

Stack Overflow用户

发布于 2018-01-26 08:55:11

这有两个部分:(1)您希望您的月份是factor而不是chr,(2)您需要按照我们通常排序月份的方式对因子进行排序。

使用一些可重现的数据:

代码语言:javascript
复制
library(ggridges)
df <- sapply(month.abb, function(x) { rnorm(10, rnorm(1), sd = 1)}) 
df <- as_tibble(x) %>% gather(key = "month")

然后您需要将月份作为一个因子,并使用由它们在data.frame中显示的实际顺序定义的级别(unique给出了数据集中的唯一级别,并按照它们在数据中的排序方式进行排序("Jan","Feb",...))。然后你需要颠倒它们,因为这样"Jan“将在底部(这是第一个因素)。

代码语言:javascript
复制
df %>% 
  # switch to factor, and define the levels they way you want them to show up 
  # in the ggplot; "Dec", "Nov", "Oct", ... 
  mutate(month = factor(month, levels = rev(unique(df$month)))) %>% 
  ggplot(aes(x = value, y = month)) + 
  geom_density_ridges()
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48454070

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档