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

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

任何关于如何解决这个问题的建议都将不胜感激。下面是我的代码:
> 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)) 发布于 2018-01-26 08:55:11
这有两个部分:(1)您希望您的月份是factor而不是chr,(2)您需要按照我们通常排序月份的方式对因子进行排序。
使用一些可重现的数据:
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“将在底部(这是第一个因素)。
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()https://stackoverflow.com/questions/48454070
复制相似问题