Как использовать символ в качестве оси x в ggplot для многострочного графика? - PullRequest
0 голосов
/ 14 июля 2020

Я пытаюсь создать ggplot, в котором по оси x у нас есть «строки», а по оси y у нас есть значения, связанные с этими строками.

В основном я хотел бы создать следующий график, но с ggplot:

введите описание изображения здесь

Я пробовал следующий код:

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()

Однако это не работает.

1 Ответ

2 голосов
/ 14 июля 2020

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.

I have also added a new order of the factor the x-Axis is made with. 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"))

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...