【问题标题】:ggplot2 histogram legend too largeggplot2 直方图图例太大
【发布时间】:2017-02-05 06:37:11
【问题描述】:

我对使用 R 获得的结果非常满意。我的大多数堆叠直方图看起来都很好,例如

但是,我有一些在图例中有太多类别,以至于图例正在挤出情节,例如

我该如何解决这个问题?

这是我的 plot.r,我像这样在命令行中调用它

RScript plot.r foo.dat foo.png 1600 800

foo.dat

account,operation,call_count,day
cal3510,foo-method,1,2016-10-01
cra4617,foo-method,1,2016-10-03
cus4404,foo-method,1,2016-10-03
hin4510,foo-method,1,2016-10-03
mas4484,foo-method,1,2016-10-04
...

整个 foo.dat:http://pastebin.com/xnJtJSrU

plot.r

library(ggplot2)
library(scales)

args<-commandArgs(TRUE)

filename<-args[1]
png_filename<-args[2]

wide<-as.numeric(args[3])
high<-as.numeric(args[4])

print(wide)
print(high)

print(filename)
print(png_filename)

dat = read.csv(filename)

dat$account = as.character(dat$account)
dat$operation = as.character(dat$operation)
dat$call_count = as.integer(dat$call_count)
dat$day = as.Date(dat$day)

png(png_filename,width=wide,height=high)

p <- ggplot(dat, aes(x=day, y=call_count, fill=account))
p <- p + geom_histogram(stat="identity")
p <- p + scale_x_date(labels=date_format("%b-%Y"), limits=as.Date(c('2016-10-01','2017-01-01')))

print(p)

dev.off()

【问题讨论】:

  • 您应该考虑删除图例。它的噪音比信息多。
  • @slashdottir 您正在阅读的 .csv 文件在哪里?
  • @aelwan 它在命令行中传递,例如foo.dat
  • 您可以将图例放在图下方theme(legend.position="bottom")
  • 还可以指定图例的行数或列数guides(fill=guide_legend(nrow=2, byrow=TRUE))

标签: r ggplot2 histogram legend stackedbarseries


【解决方案1】:

@PierreLafortune 的回答

使用:

p <- p + theme(legend.position="bottom")
p <- p + guides(fill=guide_legend(nrow=5, byrow=TRUE))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-23
    • 1970-01-01
    • 1970-01-01
    • 2014-02-21
    • 2017-07-24
    • 2013-01-13
    • 1970-01-01
    相关资源
    最近更新 更多