如何使用ggplot在一个图表中创建条形图和折线图

时间:2014-04-07 15:44:07

标签: r ggplot2

我正在尝试用ggplot创建一个条形图和折线图。这是我的数据框架dc:

structure(list(Date = structure(c(16130, 16191, 12600, 16314, 
16375, 16436, 16495, 16556, 16617, 16679, 16740, 16801), class = "Date"), 
    Lpar_Used_Pc = c(360.02, 378.02, 396.92, 416.77, 437.61, 
    459.49, 482.46, 506.58, 531.91, 558.51, 586.43, 615.76), 
    Vios = c(64L, 64L, 64L, 64L, 64L, 64L, 64L, 64L, 64L, 64L, 
    64L, 64L), Capacity = c(448L, 448L, 448L, 448L, 448L, 448L, 
    448L, 448L, 448L, 448L, 448L, 448L), Total_Used = c(424.02, 
    442.02, 460.92, 480.77, 501.61, 523.49, 546.46, 570.58, 595.91, 
    622.51, 650.43, 679.76), Percent_Used = structure(c(11L, 
    12L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L), .Label = c("102.88%", 
    "107.31%", "111.97%", "116.85%", "121.98%", "127.36%", "133.02%", 
    "138.95%", "145.19%", "151.73%", "95.00%", "98.67%"), class = "factor"), 
    Login = c(489123708, 513579893.4, 539258888.1, 566221832.5, 
    594532924.1, 624259570.3, 655472548.8, 688246176.3, 722658485.1, 
    758791409.3, 796730979.8, 836567528.8)), .Names = c("Date", 
"Lpar_Used_Pc", "Vios", "Capacity", "Total_Used", "Percent_Used", 
"Login"), row.names = c(NA, -12L), class = "data.frame")

ggplot(dc)+ geom_bar(aes(Date,Total_Used,stat="identity", position="stack"),width=0.5)+geom_line(data=dc, aes(Date,Total_Used, colour="green"))+geom_line(data=dc, aes(Date, Capacity, colour="red")

我收到一堆错误。任何想法可能会发生在这里?我还需要条形图中的登录标签。

3 个答案:

答案 0 :(得分:2)

ggplot(dc) + 
  geom_bar(aes(Date,Total_Used), stat="identity", width=0.5) +
  geom_line(data=dc, aes(Date,Total_Used, colour="green")) +
  geom_line(data=dc, aes(Date, Capacity, colour="red"))

答案 1 :(得分:1)

尝试

ggplot(dc) + 
geom_bar(aes(Date,Total_Used),stat="identity", position="stack") + 
geom_line(data=dc, aes(Date,Total_Used), colour="green") + 
geom_line(aes(Date, Capacity), colour="red")

答案 2 :(得分:1)

你有一切都非常正确,只是混淆了进出aes的内容

ggplot(dc, aes(Date,Total_Used)) +  
    geom_bar(stat="identity", position="stack",width=0.5) + 
    geom_line(colour="green") + 
    geom_line(aes(y=Capacity), colour="red")