将图例移至ggplot2的底部 [英] Moving legend to the bottom in ggplot2

查看:510
本文介绍了将图例移至ggplot2的底部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了以下热图.如果您发现同类的图例在右侧且垂直放置.

I have created the following heatmap. If you notice that the legend for cohort is on the right and the vertically placed.

如何将图例移至底部,以便为X轴变量月份M0到M55留出更多空间...此外,您会注意到X轴元素重叠,因此不清楚.

How do I move the legend to the bottom in order to give more space for X axis variable month M0 to M55...Also, you will notice that X axis elements are overlapping hence not clear.

图形输出:

cohort.clients<-df1
cohort.clients$cohort<-as.character(cohort.clients$cohort)
#we need to melt data
cohort.chart.cl <- melt(cohort.clients, id.vars = 'cohort')
colnames(cohort.chart.cl) <- c('cohort', 'month', 'clients')

#define palette
reds <- colorRampPalette(c('light green',"dark green","yellow"))

#plot data
p <- ggplot(cohort.chart.cl, aes(x=month, y=clients, group=cohort))
p + geom_area(aes(fill = cohort)) +
  scale_fill_manual(values = reds(nrow(cohort.clients))) +
  ggtitle('Customer Cohort')

推荐答案

尝试类似的方法:

ggplot(cohort.chart.cl, aes(x=month, y=clients, group=cohort))
    geom_area(aes(fill = cohort)) +
    scale_fill_manual(values = reds(nrow(cohort.clients))) +
    ggtitle('Customer Cohort') + 
    theme(axis.text.x = element_text(angle = 45, hjust = 1),
        legend.direction = "horizontal", legend.position = "bottom"))

还值得注意的是,您的调色板本质上是相同的颜色.如果您将cohort$month作为因素,则ggplot默认情况下会自动为您提供更多信息.话虽这么说,但类别超过50种时,您已经远远超出了可区分颜色的范围,并且还可能考虑将月份(分成季度或季度)进行合并,并返回到现在的光谱范围.

It's also worth noting that your color palette is essentially the same color. If you make cohort$month a factor then ggplot should automatically give you a much more informative palette by default. That being said, with >50 categories, you're well past the realm of a distinguishable colors and might also consider binning the months (into yearly quarters?) and returning to a spectrum like you have now.

这篇关于将图例移至ggplot2的底部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆