4

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

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.

Output of the graph:

Snapshot of output

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')
Vaibhav Jha
  • 99
  • 2
  • 10

1 Answers1

10

Try something like:

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"))

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.

Nancy
  • 3,989
  • 5
  • 31
  • 49