减小绘图宽度,以便不会截断图例

时间:2015-05-30 19:46:19

标签: r plot

我画的情节超出了情节区域。渲染时,图例的右侧部分将被截断。如何减小绘图宽度,以便它适合?

R plot with truncated legend

# resultValues got 9 cols and 2 rows, colors is a vector with 9 colors
# The maximal y value is 2400
# Setting width to a higher value just streches everthing
pdf("Lineplot.pdf", width = 10, height = 6)
max_y <- max(resultValues)
plot(resultValues$col1, type="o", col=colors[1], ylim=c(0,max_y), axes=FALSE,
     ann=FALSE, lwd=1.5)
axis(1, at=1:2, lab=c("2013", "2014"))
axis(2, las=1, at=250*0:max_y)
for (colname in colnames) {
  lines(resultValues[[colname]], type="o", lwd=1.5,
        col=colors[match(colname, names(resultValues))])
}
box()
par(xpd=TRUE, mar=par()$mar+c(0,0,0,6))
legend(2.05, 2500, legend=names(resultValues), ncol=1, cex=1, fill=colors,
       xjust=0, xpd=TRUE)
dev.off()
par(mar=c(5, 4, 4, 2) + 0.1)

2 个答案:

答案 0 :(得分:2)

您可以使用par(mar=...)配置更宽的右边距来解决问题。请注意,这必须在之前到主plot()次调用时完成,因为在初始plot()调用修复后,边距无法更改。

演示(使用合成数据,因为您没有提供resultValuescolors)(假设您已经设置了图形设备,例如pdf(),{{1}无论如何):

x11()

plot

答案 1 :(得分:1)

您也可以使用ggplot2。

resultValues <- data.frame(col1=c(40,70),col2=c(1710,2500),col3=c(580,280),col4=c(200,1050),col5=c(160,140),col6=c(260,10),col7=c(380,300),col8=c(380,600),col9=c(150,190))
# ^ borrowed from above :)

resultValues = rbind(t(resultValues[1,]),t(resultValues[2,]) )
resultValues = data.frame(resultValues)
resultValues$col = c(paste("col", 1:9, sep = "") , paste("col", 1:9, sep = ""))
resultValues$year = c(rep("2013",nrow(resultValues)/2),rep("2014",nrow(resultValues)/2))
names(resultValues) = c("y_value","col","year")

绘图:

require("ggplot2")

  ggplot( resultValues, aes(x = year, y = y_value, group = col) ) +
          geom_point(aes(color = col), size = 3.5,shape =1) +
          geom_line(aes(color = col)) +
          scale_x_discrete(expand = c(0.05,0.05)) +
          xlab("Year") +
          ylab("") +
          ggtitle( "Your Graph" ) +
          theme_bw() + 
          theme(   panel.grid.minor = element_blank()
                 , panel.grid.major = element_blank()
                 , legend.title=element_blank()
                 )

enter image description here