【问题标题】:Automatically resizing legend for a plot made using ggplot2 such that the entire legend lies within the boundary of the layer自动调整使用 ggplot2 绘制的图例的大小,使整个图例位于图层的边界内
【发布时间】:2014-01-24 17:50:10
【问题描述】:

我有一些数据here

我将数据读入数据框,然后使用以下代码绘制此数据,

# Reading data from a .csv file into a data frame
     df <- read.table("newcsv_file.csv",header=T,sep="\t" )
# Now melting the data frame prior to plotting     
df_mlt <- melt(df, id=names(df)[1], measure=names(df)[c(2, 6, 11,16,21,26,31,36,41,46,51,106,111,116,121,126,131,136,141,146,151)], variable = "cols")

# plotting the data
plt_fit <- ggplot(df_mlt, aes(x=x,y= value, color=cols)) +
    geom_point(size=2) +
    geom_smooth(method = "lm", se = FALSE) +
    scale_y_log10(breaks = trans_breaks("log10", function(x) 10^x), labels = trans_format("log10", math_format(10^.x))) +
    annotation_logticks(sides = "rl") +
    theme_bw() + 
    theme(legend.text=element_text(size=12), legend.title=element_text(size=12))+
    theme(axis.text=element_text(size=14)) +
    theme(axis.title=element_text(size=14,face="bold")) +
    labs(x = "x", y = "y") +
    scale_color_discrete(name = "values", labels = c("0","-0.1","-0.2","-0.3","-0.4","-0.5","-0.6","-0.7","-0.8","-0.9","-1","+0.1","+0.2","+0.3","+0.4","+0.5","+0.6","+0.7","+0.8","+0.9","+1")) +
    guides(colour = guide_legend(override.aes = list(size=3),nrow=2,title.position = 'top',title.hjust=0.5,legend.direction = "horizontal")) +
    theme(legend.position = 'bottom', legend.margin=unit(1,"cm"),legend.background = element_rect(fill ='gray94')) +
    theme(plot.margin=unit(c(0,2,0,0),"mm"))

生成的图是这样的,这里的问题是图例的最右边被裁剪了。

我使用+theme(legend.margin=unit(1,"cm")),但这似乎还不够。有人可以让我知道我可以进行哪些更改以在情节中正确显示完整的图例。

谢谢。

【问题讨论】:

    标签: r ggplot2 themes legend margins


    【解决方案1】:

    代码很好。问题是绘图窗口的大小。试着把它变宽,你会看到整个传说。

    还有,

    ggsave("plot_fit.pdf",plot_fit)
    

    将创建一个显示完整图例的 pdf。

    【讨论】:

    • @jihoward 感谢您的建议。绘图的宽度和高度必须是我保存的绘图的两倍。
    【解决方案2】:

    使用以下代码更改绘图的宽度和高度后,

    ggsave(file="new_png_file.png",width=22,height=21,units=c("cm"), dpi=600)
    

    产生这样的情节,

    【讨论】:

      猜你喜欢
      • 2013-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多