如何在ggplot中的多行旁边添加文本?

时间:2014-04-13 01:31:48

标签: r ggplot2

我正在尝试为一个情节添加几行,并在它们旁边显示文字。

Price <- seq(1, 20, by=1)
MW <- seq(1, 200, by=10)
fuel <- rep(c("Coal", "Gas", "Hydro", "Other"), each=5)
Day <- rep(1, each=20)
df1 <- data.frame(Price, MW,fuel, Day)

Price<-seq(0, 19, by=1)
MW <- seq(1, 100, by=5)
Day <- rep(2, each=20)
df2 <- data.frame(Price, MW, fuel, Day)

df <- rbind(df1, df2)
df <- df[with(df, order(Day, Price, fuel)), ]

library(ggplot2)



Lines<-data.frame(Level=c("mean", "Median"), vals=c(50, 100), lables=c("mean: 50", "Median: 100"))
Lines$valy<-10

ggplot(df, aes(x=MW, y=Price, group=Day))+
geom_point(aes(colour=fuel, shape=as.factor(Day)))+
geom_line(aes(colour=fuel))+
geom_vline(data=Lines, mapping=aes(xintercept=vals), color="blue") +
geom_text(data = Lines,
        aes(x=vals, y=valy, label=lables, colour="blue"),
        hjust = 1) 

我知道为什么会收到错误:

Error: Aesthetics must either be length one, or the same length as the dataProblems:vals, valy, lables

我也尝试在我的主数据集中执行此操作但得到错误:

object 'indexMO' not found

我的代码是:

ggplot(tSub, aes(x=cumsum, y=Price, group=indexMO))+
geom_line(aes(colour=FuelType))+
geom_point(aes(colour=FuelType))+
scale_y_continuous("Price",breaks= seq(0,1000,by=50),labels = comma_format())+
scale_x_continuous("Dispatchable Energy (MW)",breaks= seq(0,12000,by=500),labels =  comma_format())+
ggtitle(expression(atop("Minimum, Median, and Maximum Merit Orders for 2013",    atop(italic("Based on Total Dispatchable MW"), "")))) +
theme(axis.text.x = element_text(angle=-45, hjust=0, vjust=1), 
#plot.margin = unit(c(1.5, 1, 1, 1), "cm"), 
plot.title = element_text(size = 16, face = "bold", colour = "black", vjust = -1))+
theme(axis.text.x = element_text(colour = 'black', face = 'bold'))+
theme(axis.text.y = element_text(colour = 'black', face = 'bold'))+
geom_vline(data=Dispatched, mapping=aes(xintercept=vals), color="blue") +
geom_text(data = Dispatched,
        aes(x=vals, y=yval, label=LineLables, colour="blue"),
        hjust = 1) 

但这与上面的代码几乎完全相同。

2 个答案:

答案 0 :(得分:1)

这是怎么回事?

gg <- ggplot()
gg <- gg + geom_point(data=df, mapping=aes(x=MW, y=Price, group=Day, colour=fuel, shape=as.factor(Day)))
gg <- gg + geom_line(data=df, mapping=aes(x=MW, y=Price, group=Day, colour=fuel))
gg <- gg + geom_vline(data=Lines, mapping=aes(xintercept=vals), color="blue")
gg <- gg + geom_text(data=Lines, mapping=aes(x=vals, y=valy, label=as.character(lables), colour="blue"), hjust = 1) 
gg

enter image description here

因为你正在混音和匹配两个数据源&amp;美学映射,我更喜欢在每个geom中明确说明它们。这通常使R更容易处理。

答案 1 :(得分:1)

我不确定你为什么会收到这个错误,但问题是将group指定为全球美学。如果您将其移动,只有在geom_line()所需的电话中,一切正常。

ggplot(df, aes(x=MW, y=Price))+
    geom_point(aes(colour=fuel, shape=as.factor(Day)))+
    geom_line(aes(colour=fuel, group = Day))+
    geom_vline(data=Lines, mapping=aes(xintercept=vals), color="blue") +
    geom_text(data = Lines,
              aes(x=vals, y=valy, label=lables),
              color = "blue",
              hjust = 1)

这也可能是tsub的问题。