简体   繁体   English

如何在ggplot中将字符用作多线图的x轴?

[英]How to use character as x axis in ggplot for a multiple line graph?

I'm trying to make ggplot in which in the x axis we have "strings", and on y axis we have values associated to that strings.我正在尝试制作 ggplot,其中在 x 轴上我们有“字符串”,在 y 轴上我们有与该字符串关联的值。

Basically I would like to create the following graph, but with ggplot:基本上我想创建以下图表,但使用 ggplot:

在此处输入图像描述

I tried the following code:我尝试了以下代码:

dat <- data.frame(tenors = c("EONIA - DEPO", "EURIBOR 3m", "IRS 2y", "IRS 5y", "IRS 10y"),
              spot = c(-0.47, -0.42, -0.38, -0.35, -0.17),
              fwd_rates = c(-0.51, -0.46, -0.41, -0.34, -0.14),
              consensus = c(-0.50, -0.39, -0.32, -0.24, -0.03))

 theme_set(theme_minimal())
 ggplot(data.table::melt(dat, id.var = "tenors"),
 aes(x = tenors, y = dat[,2:4]), group = variable, colour = variable) + geom_line()

However it does not work.但是它不起作用。


library(ggplot2)

dat <- data.frame(tenors = c("EONIA - DEPO", "EURIBOR 3m", "IRS 2y", "IRS 5y", "IRS 10y"),
                  spot = c(-0.47, -0.42, -0.38, -0.35, -0.17),
                  fwd_rates = c(-0.51, -0.46, -0.41, -0.34, -0.14),
                  consensus = c(-0.50, -0.39, -0.32, -0.24, -0.03))



dff <- data.table::melt(dat, id.var = "tenors")

head(dat)
#>         tenors  spot fwd_rates consensus
#> 1 EONIA - DEPO -0.47     -0.51     -0.50
#> 2   EURIBOR 3m -0.42     -0.46     -0.39
#> 3       IRS 2y -0.38     -0.41     -0.32
#> 4       IRS 5y -0.35     -0.34     -0.24
#> 5      IRS 10y -0.17     -0.14     -0.03

ggplot(dff, aes(x = tenors, y = value, color = variable, group=variable)) +
  geom_line() +
  theme_minimal()


You can get the same result with tidyverse and pivot_longer .您可以使用tidyversepivot_longer获得相同的结果。

I have also added a new order of the factor the x-Axis is made with.我还添加了 x 轴所用因子的新顺序。 I did probably not chose the order you wanted, but you can just change the order in the levels of the factor.我可能没有选择您想要的顺序,但您可以更改因子级别的顺序。

library(ggplot2)
set.seed(123)
column <- c(rep(c(1),5),rep(c(2),5),rep(c(3),5),rep(c(4),5),rep(c(5),5))
row <- rep(1:5, 5)
class <- c(0,0,1,2,1,2,2,3,0,1,2,3,1,2,0,1,0,0,2,3,3,2,2,2,1)
df <- data.frame(column, row, class)
df %>% head()
#> Error in df %>% head(): konnte Funktion "%>%" nicht finden

cols <- c('0' = 'red', '1' = 'green', '2' = 'blue', '3' = 'grey')
ggplot(df, aes(column, row, fill= factor(class))) + 
  geom_tile()+
  scale_fill_manual(values = cols)+
  guides(fill=guide_legend(title="Luca`s Legend"))

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

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