【问题标题】:Plot two lines on the same y-axis; Ggplot, R在同一 y 轴上绘制两条线;格图,R
【发布时间】:2018-09-03 09:35:54
【问题描述】:

我有一个 ggplot 图,我想在上面画两条线(来自不同的列,但在同一日期)。我得到的是两条相互堆叠的线,但我希望有相同的 y 轴,正确排序,并且这些线相互重叠。

这是我要绘制的数据:

final_table:

 Month              a                      b
1 2018-04      758519.397875       2404429.258675
2 2018-05      964792.603725        1995902.14473
3 2018-06      703170.240575        1294997.84319

这是我的代码:

bla3 <- melt(final_table, id='Month')
ggplot(data=bla3, aes(x=Month, y=value, colour= variable, group=variable)) + 
  geom_line() 

我得到的输出(注意 y 轴完全错误且无序)。

【问题讨论】:

  • 看起来您的 y 变量被视为一个因素。尝试在绘图前将其转换为数字?

标签: r ggplot2


【解决方案1】:

我猜您的数据变量格式不正确。例如。如果你运行

class(final_table$month) 

这应该产生日期。所以你需要把它变成正确的格式。这是您的数字的示例。

Month <- as.character(c("2018-04", "2018-05", "2018-06")) #or convert it to character after
a <- c(758519.397875, 964792.603725, 703170.240575)
b <- c(2404429.258675, 1995902.14473, 1294997.84319)

final_table <- data.frame(Month, a, b)

 #your Month variable is messed up, you actually need the day!
 final_table$Month <- as.Date(paste(final_table$Month,"-01",sep=""))

library(reshape) #need to load that for melt
bla3 <- melt(final_table, id='Month')
ggplot(data=bla3, aes(x=Month, y=value, colour= variable, group=variable)) +   
geom_line()

【讨论】:

    猜你喜欢
    • 2015-09-01
    • 2014-05-07
    • 2015-04-04
    • 2019-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-30
    • 2016-01-11
    相关资源
    最近更新 更多