Extend bars on a ggplot2 to show the data labels not squished - r

Here is a data frame:
library(tidyverse)
example_df <- structure(list(Funnel = c("Sessions", "AddToCart", "Registrations", "ShippingDetails", "Checkout", "Transactions"), Sum = c(1437574, 385281, 148181, 56989, 35613, 29671), End = c(NA, 1437574, 385281, 148181, 56989, 35613), xpos = c(0.5, 1.5, 2.5, 3.5, 4.5, 5.5), Diff = c(NA, 1052293, 237100, 91192, 21376, 5942), Percent = c("NA %", "73.2 %", "61.5 %", "61.5 %", "37.5 %", "16.7 %")), .Names = c("Funnel", "Sum", "End", "xpos", "Diff", "Percent"), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -6L))
And here is a ggplot2:
ggplot(example_df, aes(x = reorder(Funnel, -Sum), y = Sum)) +
geom_col(alpha = 0.6, fill = "#008080") +
stat_summary(aes(label = scales::comma(..y..)), fun.y = 'sum',
geom = 'text', col = 'white', vjust = 1.5) +
geom_segment(aes(x=xpos, y = End, xend = xpos, yend = Sum)) +
geom_text(aes(x=xpos,y = End-Diff / 2, label=Percent), hjust = -0.2) +
theme(axis.title.x = element_blank(),
axis.title.y = element_blank()) +
scale_y_continuous(labels = function(l) {l = l / 1000; paste0(l, "K")}) +
Here's what it looks like:
The values on the plot from Shipping Details: Transactions are tricky to read because the bars are smaller.
I wondered if there was a good approach to dealing with this. I tried extending the range with:
+ expand_limits(y = -100000)
But that just lowers the y axis.
Is there a sensible solution to visualizing the data points in a way they are not squished? If I could somehow lower the green bars into the minus region without impacting the proportions?

Very dirty solution, but works. Add dummy geom_bar's bellow each segment (ie., extend original segment by adding negative bar) with the same color and alpha.
Bars to add:
geom_bar(data = data.frame(x = example_df$Funnel, y = -2e4),
aes(x, y),
stat = "identity", position = "dodge",
alpha = 0.6, fill = "#008080")
Final code:
# Using OPs data
library(ggplot2)
ggplot(example_df, aes(x = reorder(Funnel, -Sum), y = Sum)) +
geom_col(alpha = 0.6, fill = "#008080") +
geom_segment(aes(x=xpos, y = End, xend = xpos, yend = Sum)) +
geom_text(aes(x=xpos,y = End-Diff / 2, label=Percent), hjust = -0.2) +
theme(axis.title.x = element_blank(),
axis.title.y = element_blank()) +
scale_y_continuous(labels = function(l) {l = l / 1000; paste0(l, "K")}) +
geom_bar(data = data.frame(x = example_df$Funnel, y = -2e4),
aes(x, y),
stat = "identity", position = "dodge",
alpha = 0.6, fill = "#008080") +
stat_summary(aes(label = scales::comma(..y..)), fun.y = 'sum',
geom = 'text', col = 'white', vjust = 1.5) +
theme_classic()
Plot:
PS:
You have to add stat_summary after geom_bar

Related

How to add a vertical blank space between straight and inverted geom_density() with ggplot2

I am trying to reproduce this kind of Figure, with two densities, a first one pointing upwards and a second one pointing downwards. I would also like to have some blank space between the two densities.
Here is the code I am currently using.
library(hrbrthemes)
library(tidyverse)
library(RWiener)
# generating data
df <- rwiener(n = 1e2, alpha = 2, tau = 0.3, beta = 0.5, delta = 0.5)
df %>%
ggplot(aes(x = q) ) +
geom_density(
data = . %>% filter(resp == "upper"),
aes(y = ..density..),
colour = "steelblue", fill = "steelblue",
outline.type = "upper", alpha = 0.8, adjust = 1, trim = TRUE
) +
geom_density(
data = . %>% filter(resp == "lower"),
aes(y = -..density..), colour = "orangered", fill = "orangered",
outline.type = "upper", alpha = 0.8, adjust = 1, trim = TRUE
) +
# stimulus onset
geom_vline(xintercept = 0, lty = 1, col = "grey") +
annotate(
geom = "text",
x = 0, y = 0,
# hjust = 0,
vjust = -1,
size = 3, angle = 90,
label = "stimulus onset"
) +
# aesthetics
theme_ipsum_rc(base_size = 12) +
theme(axis.text.y = element_blank() ) +
labs(x = "Reaction time (in seconds)", y = "") +
xlim(0, NA)
Which results in something like...
How could I add some vertical space between the two densities to reproduce the above Figure?
If you want to try without faceting, you're probably best to just plot the densities as polygons with adjusted y values according to your desired spacing:
s <- 0.25 # set to change size of the space
ud <- density(df$q[df$resp == "upper"])
ld <- density(df$q[df$resp == "lower"])
x <- c(ud$x[1], ud$x, ud$x[length(ud$x)],
ld$x[1], ld$x, ld$x[length(ld$x)])
y <- c(s, ud$y + s, s, -s, -ld$y - s, -s)
df2 <- data.frame(x = x, y = y,
resp = rep(c("upper", "lower"), each = length(ud$x) + 2))
df2 %>%
ggplot(aes(x = x, y = y, fill = resp, color = resp) ) +
geom_polygon(alpha = 0.8) +
scale_fill_manual(values = c("steelblue", "orangered")) +
scale_color_manual(values = c("steelblue", "orangered"), guide = guide_none()) +
geom_vline(xintercept = 0, lty = 1, col = "grey") +
annotate(
geom = "text",
x = 0, y = 0,
# hjust = 0,
vjust = -1,
size = 3, angle = 90,
label = "stimulus onset"
) +
# aesthetics
theme_ipsum_rc(base_size = 12) +
theme(axis.text.y = element_blank() ) +
labs(x = "Reaction time (in seconds)", y = "")
you can try facetting
set.seed(123)
q=rbeta(100, 0.25, 1)
df_dens =data.frame(gr=1,
x=density(df$q)$x,
y=density(df$q)$y)
df_dens <- rbind(df_dens,
data.frame(gr=2,
x=density(df$q)$x,
y=-density(df$q)$y))
ggplot(df_dens, aes(x, y, fill = factor(gr))) +
scale_x_continuous(limits = c(0,1)) +
geom_area(show.legend = F) +
facet_wrap(~gr, nrow = 2, scales = "free_y") +
theme_minimal() +
theme(strip.background = element_blank(),
strip.text.x = element_blank(),
axis.text.y = element_blank(),
axis.title.y = element_blank())
The space between both plots can be increased using panel.spacing = unit(20, "mm"). Instead of facet_grid you can also try facet_grid(gr~., scales = "free_y")

How to add a line to connect between pies in a scatterpie plot?

I have a scatterpie plot with pies plotted over x and y axes. How can I add straight lines that connect between pies? Ideally, I would want the lines to connect the y-values underlying the center points of the pies.
I tried adding geom_path but it didn't work out.
This question is a follow-up on this question I posted before.
My Data
library(tidyverse)
library(scatterpie)
my_df <- structure(list(day_in_july = 13:20, yes_and_yes = c(0.611814345991561,
0.574750830564784, 0.593323216995448, 0.610539845758355, 0.650602409638554,
0.57429718875502, 0.575971731448763, 0.545454545454545), yes_but_no = c(0.388185654008439,
0.425249169435216, 0.406676783004552, 0.389460154241645, 0.349397590361446,
0.42570281124498, 0.424028268551237, 0.454545454545455), y = c(0.388185654008439,
0.425249169435216, 0.406676783004552, 0.389460154241645, 0.349397590361446,
0.42570281124498, 0.424028268551237, 0.454545454545455)), row.names = c(NA,
-8L), class = c("tbl_df", "tbl", "data.frame"))
My current scatterpie plot
p <- ggplot(data = my_df) +
geom_scatterpie(aes(x = day_in_july, y = y*50, r = 0.3),
data = my_df,
cols = colnames(my_df)[2:3],
color = "red") +
geom_text(aes(y = y*50, x = day_in_july,
label = paste0(formatC(y*100, digits = 3), "%")),
nudge_y = 0.07, nudge_x = -0.25, size = 3) +
geom_text(aes(y = y*50, x = day_in_july,
label = paste0(formatC((1-y)*100, digits = 3), "%")),
nudge_y = -0.07, nudge_x = 0.25, size = 3) +
scale_fill_manual(values = c("pink", "seagreen3")) +
scale_x_continuous(labels = xvals, breaks = xvals) +
scale_y_continuous(name = "yes but no",
labels = function(x) x/50) +
coord_fixed()
> p
I want to connect the pies to express a trend over time, such as the following:
Basically, I want to connect the y-values behind each pie, in a way that the line will be behind the pies.
I tried adding geom_path(). But it didn't work and I just get the same plot with no line. Also tried geom_line without success.
p + geom_path(x = as.numeric(my_df$day_in_july), y = my_df$yes_but_no)
Just add geom_path with the same x and y aesthetics at the beginning of your code:
p <- ggplot(data = my_df) +
geom_path(aes(x = day_in_july, y = y*50)) +
geom_scatterpie(aes(x = day_in_july, y = y*50, r = 0.3),
data = my_df,
cols = colnames(my_df)[2:3],
color = "red") +
geom_text(aes(y = y*50, x = day_in_july,
label = paste0(formatC(y*100, digits = 3), "%")),
nudge_y = 0.07, nudge_x = -0.25, size = 3) +
geom_text(aes(y = y*50, x = day_in_july,
label = paste0(formatC((1-y)*100, digits = 3), "%")),
nudge_y = -0.07, nudge_x = 0.25, size = 3) +
scale_fill_manual(values = c("pink", "seagreen3")) +
# scale_x_continuous(labels = xvals, breaks = xvals) +
scale_y_continuous(name = "yes but no",
labels = function(x) x/50) +
coord_fixed()

How to add common line and text as second x-axis label

I want to plot a graph. Several of my x-axis labels have a common label. So I want to add common text as label instead of several separate labels on x-axis as shown in the attached images. How can this be done?
library(dplyr)
library(forcats)
library(ggplot2)
df <- data.frame(conc = c(0, 10, 50, 100, "Positive Control"),
values = c(3, 3, 4, 5, 10),
name = c("TiO2 NP", "TiO2 NP", "TiO2 NP", "TiO2 NP", "Cyclophosamide"))
df$conc <- as.factor(df$conc)
labels2 <- paste0(df$conc, "\n", df$name)
df %>%
mutate(conc = fct_reorder(conc, values)) %>%
ggplot(aes(x = conc, y=values, fill = conc))+
geom_bar(stat = "identity",show.legend = FALSE, width = 0.6)+
scale_x_discrete(labels = labels2)+
labs(x = "\n Dose (mg/kg BW)")
I don't think there's a simple way. You have to play with ggplot2 for some time to make something really custom. Here's my example:
df %>%
mutate(
conc = fct_reorder(conc, values),
labels2 = if_else(
name == 'TiO2 NP',
as.character(conc),
paste0(conc, '\n', name)
)
) %>%
ggplot(aes(x=conc, y=values, fill = conc)) +
geom_bar(
stat = "identity",
show.legend = FALSE,
width = 0.6
) +
geom_rect(aes(
xmin = .4,
xmax = 5.6,
ymin = -Inf,
ymax = 0
),
fill = 'white'
) +
geom_text(aes(
y = -.4,
label = labels2
),
vjust = 1,
size = 3.4,
color = rgb(.3, .3, .3)
) +
geom_line(data = tibble(
x = c(.9, 4.1),
y = c(-1.2, -1.2)
),
aes(
x = x,
y = y
),
color = rgb(.3, .3, .3),
inherit.aes = FALSE
) +
geom_curve(data = tibble(
x1 = c(.8, 4.1),
x2 = c(.9, 4.2),
y1 = c(-.8, -1.2),
y2 = c(-1.2, -.8)
),
aes(
x = x1,
y = y1,
xend = x2,
yend = y2
),
color = rgb(.3, .3, .3),
inherit.aes = FALSE
) +
geom_text(aes(
x = 2.5,
y = -1.7,
label = 'TiO2 NP'
),
size = 3.4,
color = rgb(.3, .3, .3),
check_overlap = TRUE
) +
geom_text(aes(
x = 3,
y = -2.4,
label = '\n Dose (mg/kg BW)'
),
show.legend = FALSE,
check_overlap = TRUE
) +
theme_minimal() +
theme(
axis.text.x = element_blank(),
axis.title.x = element_blank()
) +
scale_y_continuous(
breaks = seq(0, 10, 2.5),
limits = c(-2.5, 10)
)
For a more automated approach, you can try placing the common variable in facet_grid with scales = "free", space = "free", to simulate a 2nd x-axis line. The rest of the code below are for aesthetic tweaks:
df %>%
mutate(conc = fct_reorder(conc, values)) %>%
ggplot(aes(x = conc, y = values, fill = conc)) +
geom_col(show.legend = F, width = 0.6) + #geom_col() is equivalent to geom_bar(stat = "identity")
facet_grid(~ fct_rev(name),
scales = "free", space = "free",
switch = "x") + #brings the facet label positions from top (default) to bottom
scale_x_discrete(expand = c(0, 0.5)) + #adjusts the horizontal space at the ends of each facet
labs(x = "\n Dose (mg/kg BW)") +
theme(axis.line.x = element_line(arrow = arrow(ends = "both")), #show line (with arrow ends) to
#indicate facet label's extent
panel.spacing = unit(0, "cm"), #adjusts space between the facets
strip.placement = "outside", #positions facet labels below x-axis labels
strip.background = element_blank()) #transparent background for facet labels

Drawing elements (arrows & circle) in ggplot (R) to show the difference between two bars

I am trying to create a plot in R using ggplot that shows the difference between my two bars in a nice way.
I found an example that did part of what I wanted, but I have two major problems:
It is based on comparing groups of bars, but I only have two, so I added one group with both of them.
I would like to draw the arrow in nicer shape. I attached an image.
Code:
transactions <- c(5000000, 1000000)
time <- c("Q1","Q2")
group <- c("A", "A")
data <- data.frame(transactions, time, group)
library(ggplot2)
fun.data <- function(x){
print(x)
return(data.frame(y = max(x) + 1,
label = paste0(round(diff(x), 2), "cm")))
}
ylab <- c(2.5, 5.0, 7.5, 10)
gg <- ggplot(data, aes(x = time, y = transactions, fill = colors_hc[1], label = round(transactions, 0))) +
geom_bar(stat = "identity", show.legend = FALSE) +
geom_text(position = position_dodge(width = 0.9),
vjust = 1.1) +
geom_line(aes(group = group), position = position_nudge(0.1),
arrow = arrow()) +
stat_summary(aes(x = group, y = transactions),
geom = "label",
fun.data = fun.data,
fontface = "bold", fill = "lightgrey",
inherit.aes = FALSE) +
expand_limits(x = c(0, NA), y = c(0, NA)) +
scale_y_continuous(labels = paste0(ylab, "M"),
breaks = 10 ^ 6 * ylab)
gg
The arrows I am aiming for:
Where I am (ignore the ugliness, didn't style it yet):
This works, but you still need to play around a bit with the axes (or rather beautify them)
library(dplyr)
library(ggplot2)
transactions <- c(5000000, 1000000)
time <- c("Q1","Q2")
group <- c("A", "A")
my_data <- data.frame(transactions, time, group)
fun.data <- function(x){
return(data.frame(y = max(x) + 1,
label = as.integer(diff(x))))
}
my_data %>%
ggplot(aes(x = group, y = transactions, fill = time)) +
geom_bar(stat = 'identity', position = 'dodge') +
geom_text(aes(label = as.integer(transactions)),
position = position_dodge(width = 0.9),
vjust = 1.5) +
geom_line(aes(group = group), position = position_nudge(0.1),
arrow = arrow()) +
stat_summary(aes(x = group, y = transactions),
geom = "label",
size = 5,
position = position_nudge(0.05),
fun.data = fun.data,
fontface = "bold", fill = "lightgrey",
inherit.aes = FALSE)
Edit2:
y_limit <- 6000000
my_data %>%
ggplot(aes(x = time, y = transactions)) +
geom_bar(stat = 'identity',
fill = 'steelblue') +
geom_text(aes(label = as.integer(transactions)),
vjust = 2) +
coord_cartesian(ylim = c(0, y_limit)) +
geom_segment(aes(x = 'Q1', y = max(my_data$transactions),
xend = 'Q1', yend = y_limit)) +
geom_segment(aes(x = 'Q2', y = y_limit,
xend = 'Q2', yend = min(my_data$transactions)),
arrow = arrow()) +
geom_segment(aes(x = 'Q1', y = y_limit,
xend = 'Q2', yend = y_limit)) +
geom_label(aes(x = 'Q2',
y = y_limit,
label = as.integer(min(my_data$transactions)- max(my_data$transactions))),
size = 10,
position = position_nudge(-0.5),
fontface = "bold", fill = "lightgrey")

Replace the mapping text in ggplotly() plot without breaking the plot

I am creating a stacked bar chart below using ggplot and I convert it to interactive using ggplotly(). As you can see in the screenshot below the pop up text when I hover over a bar shows as "Name" the correct "Name" of the relative bar-in that case- DCH. I tried to replace that with a name of my choice but then the whole chart breaks down. So basically I would like to know if I can use "Name" in the background in order to display the chart but display another Name instead. The same for all of the 5 bars.
The code chunk which is related with this is:
geom_col(mapping = aes(x = Name, y = count, fill = Class), width = rep(0.9,5),
color = "black", position = position_fill(reverse = T)) +
geom_text(size = 4, position = position_fill(reverse = T, vjust = 0.50), color = "black",
mapping = aes(x = Name, y = count, group = Class, label = round(count))) +
#DATA
Name<-c("DCH","DCH","DCH","DGI","DGI","DGI","LDP","LDP","LDP","RH","RH","RH","TC","TC","TC")
Class<-c("Class1","Class2","Overlap","Class1","Class2","Overlap","Class1","Class2","Overlap","Class1","Class2","Overlap","Class1","Class2","Overlap")
count<-c(2077,1642,460,1971,5708,566,2316,810,221,2124,3601,413,2160,1097,377)
FinalDF<-data.frame(Name, Class,count)
#PLOT
ggplotly(ggplot(data = FinalDF) +
geom_col(mapping = aes(x = Name, y = count, fill = Class), width = rep(0.9,5),
color = "black", position = position_fill(reverse = T)) +
geom_text(size = 4, position = position_fill(reverse = T, vjust = 0.50), color = "black",
mapping = aes(x = Name, y = count, group = Class, label = round(count))) +
annotate('text', size = 5, x = (5+1)/2, y = -0.1, label = c('A'), angle = 90) +
coord_flip() +
scale_fill_manual(values = c('lemonchiffon', 'palegreen3', 'deepskyblue2'),breaks=c("Class1", "Overlap", "Class2"), labels = c(paste("Unique to","DB"), "Overlap", "Unique to Comparison Dataset "),
guide = guide_legend(label.position = 'left', label.hjust = 0, label.vjust = 0.5)) )
The tooltip argument might be in the right direction.
library(sf)
library(plotly)
# Create the stacked bar plot using ggplot()
stackedBarPlot<- ggplot(data = FinalDF) +
geom_col(mapping = aes(x = Name, y = count, fill = Class), width = rep(0.9,5),
color = "black", position = position_fill(reverse = T)) +
geom_text(size = 4, position = position_fill(reverse = T, vjust = 0.50), color = "black",
mapping = aes(x = Name, y = count, group = Class, label = round(count))) +
annotate('text', size = 5, x = (5+1)/2, y = -0.1, label = c('A'), angle = 90) +
coord_flip() +
scale_fill_manual(values = c('lemonchiffon', 'palegreen3', 'deepskyblue2'),breaks=c("Class1", "Overlap", "Class2"), labels = c(paste("Unique to","DB"), "Overlap", "Unique to Comparison Dataset "),
guide = guide_legend(label.position = 'left', label.hjust = 0, label.vjust = 0.5))+
geom_sf(aes(fill=Class,text=paste(Name,"DB")))
stackedBarPlot%>%
ggplotly(tooltip = "text")

Resources