Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pipe ggplot2 w/ dynamic title

Tags:

r

pipe

ggplot2

Can I get to the data and make a title with a pipe in a ggplot?

Say I have data like this,

x <- c(5,17,31,9,17,10,30,28,16,29,14,34)
y <- c(1,2,3,4,5,6,7,8,9,10,11,12)
day <- c(1,2,3,4,5,6,7,8,9,10,11,12)

df2 <- reshape2::melt(df1, id.vars='day') %>% data.frame(x, y, day, company = 'inc. company name ')

df2 %>% ggplot(aes(x=day, y=value, fill=variable), xlab="Age Group") + 
  geom_bar(stat = "identity", position = "dodge", width = 0.5) 

wher I'm at

However I would like to do something like this

df2 %>% ggplot(aes(x=day, y=value, fill=variable), xlab="Age Group") + 
  geom_bar(stat = "identity", position = "dodge", width = 0.5) +
  + labs(title = paste0(.$company, "numbers")) # NOT WOKRING CODE

To get to this, wher eI would like to go

like image 248
Eric Fail Avatar asked Sep 15 '25 15:09

Eric Fail


1 Answers

You can fence in the entire ggplot2 bit in a single expression, which allows you to use the . pronoun throughout ggplot2 calls. I don't see why you'd want to do this except for saving 2 keystrokes, but you could.

library(tidyverse)

x <- c(5,17,31,9,17,10,30,28,16,29,14,34)
y <- c(1,2,3,4,5,6,7,8,9,10,11,12)
day <- c(1,2,3,4,5,6,7,8,9,10,11,12)

df1 <- data.frame(x = x, y = y, day = day)

df2 <- reshape2::melt(df1, id.vars='day') %>% data.frame(x, y, day, company = 'inc. company name ')

df2 %>% {
  ggplot(., aes(x=day, y=value, fill=variable), xlab="Age Group") + 
    geom_bar(stat = "identity", position = "dodge", width = 0.5) +
    labs(title = paste0(.$company, "numbers"))
}

Created on 2021-02-08 by the reprex package (v1.0.0)

like image 140
teunbrand Avatar answered Sep 18 '25 06:09

teunbrand