How to plot two columns in a stacked barplot - r

I would appreciate your help in the following: I'm trying to build a stacked barplot. The fill is the split of business (new and renewed), the Y axis is volume of new/renewed business and the X would be the month. In my data I have two years of history, so I would like to have two stacked columns per month, one for n-1 year and one for n year. However, I don't know how to do this last step...
To clarify, please find below a picture of the data, the plot I have so far and a drawing of my goal.
And here is the code:
ggplot(BUSINESS, aes(fill=Business, y=GWP_mio, x=Date)) +
geom_bar(position="stack", stat="identity") +
scale_fill_manual(values = c("#009E73","Darkblue")) +
scale_y_continuous(breaks=seq(0,18000000,1000000), labels = scales::comma_format(scale = 1/1000000,
accuracy = .1), limits = c(0,18000000)) +
theme_ipsum() +
ggtitle('GWP development') +
theme(plot.title = element_text(hjust=0.5, size=14, family="Calibri", face="bold"),
legend.title = element_text(size=11, family="Calibri", face="bold"),
axis.title.x = element_text(hjust=1, size=11, family="Calibri", face="bold"),
axis.text.x = element_text(angle=90, hjust=1, size=11, family="Calibri"),
axis.title.y = element_text(angle=0, hjust=1, size=10, family="Calibri", face="bold"))
Any help would be highly appreciated.
[2
[]3

What you're asking for is both position= 'dodge' and position= 'stack'. I'd actually suggest using faceting:
Data
library(data.table)
library(ggplot2)
N <- 24
dat <- data.table(
date= rep(seq.Date(as.Date('2017-01-01'), as.Date('2018-12-01'), '1 month'), each= 2)
, new= rpois(n= 2 * N, lambda= 5)
, renew= rpois(n= 2 * N, lambda= 4)
)
dat[,year := data.table::year(date)]
dat[,month:= data.table::month(date)]
dat <- melt(dat, id.vars= c("date", "year", "month"), variable.name= 'business_type', value.name= 'units')
Facet
This is going to be much easier for the viewer.
ggplot(dat, aes(x= month, y= units, fill= factor(year))) +
geom_bar(position= 'dodge', stat='identity') + facet_grid(business_type ~ .) +
theme(axis.text.x= element_text(angle= 90))
Solution
But that's not what you asked for. So let's do something hacky. You'll have to mess around with the colours / fill to get exactly what you want. But here we add a first layer for the total, then a second layer for the new
N <- 24
dat <- data.table(
date= rep(seq.Date(as.Date('2017-01-01'), as.Date('2018-12-01'), '1 month'), each= 2)
, new= rpois(n= 2 * N, lambda= 5)
, renew= rpois(n= 2 * N, lambda= 4)
)
dat[,year := data.table::year(date)]
dat[,month:= data.table::month(date)]
dat[, total := new + renew]
ggplot(dat, aes(x= month, y= total, fill= factor(year))) +
geom_bar(stat= 'identity', position= 'dodge', ) +
geom_bar(data= dat, aes(x= month, y= new, fill= "black", colour= factor(year)), stat= 'identity', position= 'dodge') +
scale_color_brewer(palette = "Dark2")

Related

Multiple plots in one figure in R

I have three plots and I want to show them in a figure like below
link
I made a few attempts but I was not successful. My codes are given below:
dat <- read.table(text="
dates PS.230 PS.286 PS.389
3.01.2018 20.75103 16.69312 -6.503637
15.01.2018 15.00284 16.03211 16.1058
8.02.2018 11.0789 7.438522 -2.970704
20.02.2018 15.10865 12.8969 3.935687
4.03.2018 24.74799 19.25148 9.186779
28.03.2018 -1.299456 7.028817 -8.126284
9.04.2018 4.778902 8.309322 -3.450085
21.04.2018 7.131915 9.484932 -4.326919
", header=T, stringsAsFactors=FALSE)
dat$dates <- as.Date(dat$dates, "%d.%m.%Y")
library(ggplot2)
library(tidyverse)
a <- ggplot(dat, aes(x=dates, y=PS.230)) +
geom_point() +
geom_line() +
geom_smooth(se = FALSE, method = lm, size = 0.15, color = "#da0018") + #cizgi eklemek icin
scale_x_date(date_breaks = "1 months",date_labels = "%Y-%m",
limits = as.Date.character(c("01/12/2017","31/12/2018"),
format = "%d/%m/%Y")) +
ylim(-20,40) +
ylab("[mm/year]") +
xlab("") +
theme_linedraw() #theme_light
a + theme(
axis.text.x = element_text(angle = 45, hjust = 1),
panel.grid.major.x = element_blank(),
panel.grid.minor.x = element_blank()
)
b <- ggplot(dat, aes(x=dates, y=PS.286)) +
geom_point() +
geom_line() +
geom_smooth(se = FALSE, method = lm, size = 0.15, color = "#da0018") + #cizgi eklemek icin
scale_x_date(date_breaks = "1 months",date_labels = "%Y-%m",
limits = as.Date.character(c("01/12/2017","31/12/2018"),
format = "%d/%m/%Y")) +
ylim(-20,40) +
ylab("[mm/year]") +
xlab("") +
theme_linedraw() #theme_light
b + theme(
axis.text.x = element_text(angle = 45, hjust = 1),
panel.grid.major.x = element_blank(),
panel.grid.minor.x = element_blank()
)
c <- ggplot(dat, aes(x=dates, y=PS.389)) +
geom_point() +
geom_line() +
geom_smooth(se = FALSE, method = lm, size = 0.15, color = "#da0018") + #cizgi eklemek icin
scale_x_date(date_breaks = "1 months",date_labels = "%Y-%m",
limits = as.Date.character(c("01/12/2017","31/12/2018"),
format = "%d/%m/%Y")) +
ylim(-20,40) +
ylab("[mm/year]") +
xlab("") +
theme_linedraw() #theme_light
c + theme(
axis.text.x = element_text(angle = 45, hjust = 1),
panel.grid.major.x = element_blank(),
panel.grid.minor.x = element_blank()
)
in the link I provided, much better graphics were drawn with fewer lines. my codes seem a little more complicated and frankly i couldn't get out. a, b and c plots in one image and only one date axes. How can I modify the codes to achieve sample result? Thank you.
Thank you for posting your data. As mentioned, the first step is to arrange your dataset so that it is in Tidy Data format. The information in dat$PS.230, dat$PS.286 and dat$PS.389 should be better represented in two columns:
First Column: name of data type - We'll call this column dat$value_type and it will have values that indicate if dat$results comes from PS.230, PS.286, or PS.389.
Second Column: value of data - We'll call this column dat$result and it just shows the value. This will be the y= aesthetic for all plots.
Pre-Processing: Gather into TidyData format
Use the gather() function to gather all columns in to a key ("value_type") and a "value" ("result"). We'll gather all columns except for "dates", so we just note to exclude that column via -dates:
dat <- dat %>% gather(key='value_type', value='result', -dates)
Plot
For the plot, you apply x and y aesthetics to "date" and "result". You can use "value_type" to differentiate based on color and create your legend for points and lines. You also use "value_type" as the column for creating the facets (the three separate plots) via use of facet_grid() function. Note that value_type ~ . arranges by "value_type" vertically, whereas . ~ value_type would arrange horizontally:
ggplot(dat, aes(x=dates, y=result)) +
geom_line(aes(color=value_type)) +
geom_point(aes(color=value_type)) +
scale_x_date(date_breaks = '1 months', date_labels = '%Y-%m') +
facet_grid(value_type ~ .) +
theme_bw()

How to use scale_x_date properly

I am a new user in R and I hope you can help me.
setwd("C:/Users/USER/Desktop/Jorge")
agua <- read_excel("agua.xlsx")
pbi <- read_excel("PBIagro.xlsx")
str(agua);
names(agua)[2] <- "Variación";
agua[,1] <- as.Date(agua$Trimestre)
lagpbi <- lag(pbi$PBIAgropecuario, k=1)
pbi[,3]<- lagpbi; pbi <- pbi[-c(1),];
names(pbi)[3] <- "PBIlag"
growth <- ((pbi$PBIAgropecuario-pbi$PBIlag)/pbi$PBIlag)*100
Anual_growth <- data.frame(growth); Anual_growth[,2] <- pbi$Año; names(Anual_growth)[2] <- "Año"
# Plot
Agro <- ggplot(Anual_growth, aes(x=Año, y=growth)) +
geom_line(color="steelblue") +
geom_point() +
geom_text(aes(label = round(Anual_growth$growth, 1)),
vjust = "inward", hjust = "inward", size=2.5, show.legend = FALSE) +
xlab("") +
theme_ipsum() +
theme(axis.text.x=element_text(angle=60, hjust=1)) +
ylim(-9.9,13.4) +
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
axis.line.x = element_blank(), plot.margin = unit(c(1,1,0.5,1),"cm"),
axis.line.y = element_blank(), axis.text.x=element_text(face = "bold", size=8,
angle=1,hjust=0.95,vjust=0.2),
axis.text.y = element_blank(), axis.title.y=element_blank())+
scale_x_continuous("Año", labels = as.character(Anual_growth$Año), breaks = Anual_growth$Año)
print(Agro)
The problem is that it shows all the years, but I only want pair years (in X-axis) or years with step equal to 2.
I hope you can really help me.
Thank you.
Notice that the X-axis variable is a numeric string.
You can add something like
scale_x_date(date_breaks = "2 years", date_labels = "%Y") to your ggplot.
This is how it looks with my data, since you haven't posted yours. I am plotting a type date on x axis.
1.
ggplot(mydata) +
aes(x = date, y = number, color = somevar) +
geom_line()
ggplot(mydata) +
aes(x = date, y = number, color = somevar) +
geom_line() +
scale_x_date(date_breaks = "1 year", date_labels = "%Y")
3.
ggplot(mydata) +
aes(x = date, y = number, color = somevar) +
geom_line() +
scale_x_date(date_breaks = "2 years", date_labels = "%Y")
If you want pair years and because your x-axis variable is numeric, you can specify in scale_x_continous that breaks argument should take only even numbers.
Here how you can do it using this small example:
year = 1998:2020
value = rnorm(23,mean = 3)
df = data.frame(year,value)
library(ggplot2)
ggplot(df, aes(x = year, y = value))+
geom_point()+
geom_line()+
scale_x_continuous(breaks = year[year %%2 ==0])
Reciprocally, if you want odd years, you just have to specify scale_x_continuous(breaks = year[year %%2 != 0])
So, in your code, you should write:
scale_x_continuous(breaks = Anual_growth$Año[Anual_growth$Año %%2 ==0])
Does it answer your question ?

Changing x-axis labels in ggplot

I have a bar plot that has 12 x values. Using this code I get the plot I want except for the x-axis labels.
p <- ggplot(data=df.mean, aes(x=stock_name, y=invest_amnt, fill=trend_id)) +
geom_bar(stat="identity", position=position_dodge()) +
geom_errorbar(aes(ymin=invest_amnt-ic, ymax=invest_amnt+ic), width=.2,
position=position_dodge(.9))
p + scale_fill_brewer(palette="Paired") + theme_minimal() +
theme(text = element_text(size=12, hjust = 0.5, family="Times")) +
theme_stata() + scale_color_stata()
Instead of displaying all 12 values on the x-axis I want to determine the labels by myself and only display 4.
I adjusted the code like this
p <- ggplot(data=df.mean, aes(x=stock_name, y=invest_amnt, fill=trend_id)) +
geom_bar(stat="identity", position=position_dodge()) +
geom_errorbar(aes(ymin=invest_amnt-ic, ymax=invest_amnt+ic), width=.2,
position=position_dodge(.9)) +
scale_x_discrete( labels=c("UP\nDOWN", "DOWN\nUP", "STRAIGHT\nGAIN", "STRAIGHT\nLOSS")) +
scale_fill_discrete(name = "Trend", labels = c("negative", "flat", "positive"))
p + scale_fill_brewer(palette="Paired") + theme_minimal() +
theme(text = element_text(size=12, hjust = 0.5, family="Times")) +
theme_stata() + scale_color_stata()
Unfortunately, I get my 4 labels but also 8 NAs. I would like my 4 labels to be evenly spread on my x-axis. Since my labels are factors I do not know how to apply break here.
I've generated some sample data...hope I've understood the situation correctly.
This seems to work, i.e. inserts breaks at the specified locations on a barplot, using the specified labels.
library(tidyverse)
df <- tribble(~x, ~y,
'cat',10,
'dog', 20,
'rabbit', 30,
'fox', 30)
df <- df %>%
mutate(x = factor(x))
df %>% ggplot(aes(x,y))+
geom_bar(stat = 'identity') +
scale_x_discrete(breaks = c('cat','fox'), labels = c('pig', 'hen'))

Grouped bar chart, ggplot2 in R, need to display one observation at a time

I have a dataset that looks like the following:
df <- data.frame(Name=rep(c('Sarah', 'Casey', 'Mary', 'Tom'), 3),
Scale=rep(c('Scale1', 'Scale2', 'Scale3'), 4),
Score=sample(1:7, 12, replace=T))
I am trying to create a barchat in ggplot2 that currently looks like this:
ggplot(df, aes(x=Name, y=Score, fill=Scale)) + geom_bar(stat='identity', position='dodge') +
coord_flip() +
scale_y_continuous(breaks=seq(0, 7, 1), limits = c(0, 7)) +
scale_x_discrete() +
scale_fill_manual(values=c('#253494', '#2c7fb8', '#000000')) +
theme(panel.background = element_blank(),
legend.position = 'right',
axis.line = element_line(),
axis.title = element_blank(),
axis.text = element_text(size=10))
However, I only want to show one observation (one Name) at a time. Is this possible to do without creating a ton of separate datasets, one for each person? I would like the end result to look like the example below, where I can just iterate through the names to produce a separate plot for each, or some similar process.
# Trying to avoid creating separate datasets, but for the sake of the example:
df2 <- data.frame(Name=rep(c('Sarah'), 3),
Scale=c('Scale1', 'Scale2', 'Scale3'),
Score=sample(1:7, 3, replace=T))
ggplot(df2, aes(x=Name, y=Score, fill=Scale)) + geom_bar(stat='identity', position='dodge') +
coord_flip() +
scale_y_continuous(breaks=seq(0, 7, 1), limits = c(0, 7)) +
scale_x_discrete() +
scale_fill_manual(values=c('#253494', '#2c7fb8', '#000000')) +
theme(panel.background = element_blank(),
legend.position = 'right',
axis.line = element_line(),
axis.title = element_blank(),
axis.text = element_text(size=10))
Since your data is already tidy ie. in long format, you can use facet_wrap as suggested and set the scales as "free" thus creating facets with your different Name groups.
df %>% ggplot(aes(y = Score, x = Name)) +
geom_bar(stat = "identity", aes(colour = Scale, fill = Scale),
position = "dodge") +
coord_flip() +
facet_wrap(~Name, scales = "free")
You can get rid of the facet labels or the axis labels depending which you prefer.
EDIT: in response to comment.
You can use the same data frame to create seperate plots by just piping a filter in at the start, hence,
df %>%
filter(Name == "Sarah") %>%
ggplot(aes(y = Score, x = Name)) +
geom_bar(stat = "identity", aes(colour = Scale, fill = Scale),
position = "dodge") +
coord_flip()
Since you are using Rmarkdown you could throw a for loop around that to plot all the names
for(i in c("Sarah", "Casey", "Mary", "Tom")){
df %>%
filter(Name == i) %>%
ggplot(aes(y = Score, x = Name)) +
geom_bar(stat = "identity", aes(colour = Scale, fill = Scale),
position = "dodge") +
coord_flip()
}
If you want to arrange all these into a group you can use ggpubr::ggarrange to place all the plots into the same object.
facet_grid(.~Name)
Maybe somehow implement this, it'll plot them all, but should do so in individual plots.

Trim first and last labels in ggplot2

I've got a plot that is tabulating two types of data by day and I'm looking to just trim the first and last label from the plot. Here is a reproducible example of the data:
library(dplyr)
library(ggplot2)
library(scales)
dates <- paste0("2014-01-", 1:31)
dat <- data.frame("Date" = sample(dates, 4918, replace=T),
"Type" = sample(c('Type1', 'Type2'), 4918, replace=T, probs=c(.55, .45)))
p.data <- dat %>% group_by(Date, Type) %>% summarise(Freq = n())
p.data$Date <- as.Date(p.data$Date)
Here is the code for the plot:
p <- ggplot(data=p.data, aes(x=Date, y=Freq, fill=Type)) +
geom_bar(stat='identity', position='dodge') +
labs(x='Date', y='Count', title='Frequency of Data by Day') +
theme_bw() +
theme(axis.text.x = element_text(angle=90),
panel.grid.minor = element_blank(),
plot.title = element_text(vjust=1.4),
legend.position='bottom') +
scale_x_date(labels=date_format("%a %d"),
breaks=date_breaks("day"),
limits=c(as.Date('2014-01-01'), as.Date('2014-01-31'))) +
scale_y_continuous(limits=c(0, 150), breaks=seq(from=0, to=150, by=25)) +
scale_fill_manual(values=c('dark grey', 'light green'))
As you can see, there are two label points for the day prior to the beginning of the month and the day after the last day of the month. How do I trim those off? Can I just subset the labels and breaks call in scale_x_date()?
The expand argument in scale_x_date is one way to do it. It tries to be helpful by making some extra space around the edges, but in this case it adds more than a day, so the axis labels have those extra days.
p <- ggplot(data=p.data, aes(x=Date, y=Freq, fill=Type)) +
geom_bar(stat='identity', position='dodge') +
labs(x='Date', y='Count', title='Frequency of Data by Day') +
theme_bw() +
theme(axis.text.x = element_text(angle=90),
panel.grid.minor = element_blank(),
plot.title = element_text(vjust=1.4),
legend.position='bottom') +
scale_x_date(labels=date_format("%a %d"),
breaks=date_breaks("day"),
limits=c(as.Date('2014-01-01'), as.Date('2014-01-31')),
expand=c(0, .9)) +
scale_y_continuous(limits=c(0, 150), breaks=seq(from=0, to=150, by=25)) +
scale_fill_manual(values=c('dark grey', 'light green'))

Resources