简体   繁体   中英

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.

Basically I would like to create the following graph, but with 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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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