gghighlight prints label_key - r

I am plotting a bar graph using ggplot2 and highlighting particular bars using gghighlight.
But using gghighlight prints some label_key also in the output.
I want to remove the label_key printed on top plot.
Please help.
ggplot(data=plot, aes(x=subdomain_name, y=mean)) +
geom_bar(stat="identity", color="blue", fill="blue",width = nrow(plot)/10)+
geom_text(aes(label=format(round(mean,2))),hjust=0)+
coord_flip() + theme(axis.line = element_blank(),axis.line.x = element_blank(),
axis.line.y = element_blank(),plot.margin=unit(c(-0.6,1,1,1),"cm"),
panel.background=element_blank(),panel.border=element_blank(),
axis.title.x = element_blank(),axis.title.y = element_blank() )
+ylim(0,max+(0.05*max)) + gghighlight(grepl('Domain',subdomain_name),
unhighlighted_colour = alpha("red",1),
label_key = NULL))

In this case, you need use_direct_label = FALSE.
library(ggplot2)
library(gghighlight)
plot <- data.frame(
subdomain_name = c(paste("Domain ", letters[1:3]), "foo"),
mean = 1:4
)
max <- 4
ggplot(data = plot, aes(x = subdomain_name, y = mean)) +
geom_bar(stat = "identity", color = "blue", fill = "blue", width = nrow(plot) / 10) +
geom_text(aes(label = format(round(mean, 2))), hjust = 0) +
coord_flip() +
theme(
axis.line = element_blank(), axis.line.x = element_blank(),
axis.line.y = element_blank(), plot.margin = unit(c(-0.6, 1, 1, 1), "cm"),
panel.background = element_blank(), panel.border = element_blank(),
axis.title.x = element_blank(), axis.title.y = element_blank()
) +
ylim(0, max + (0.05 * max)) +
gghighlight(grepl("Domain", subdomain_name),
unhighlighted_colour = alpha("red", 1),
use_direct_label = FALSE
)
Created on 2018-12-23 by the reprex package (v0.2.1)

You should set label_key to F like this: You can also try using ?guides
library(gghighlight)
ggplot(data=plot, aes(x=subdomain_name, y=mean)) +
geom_bar(stat="identity", color="blue", fill="blue",width = nrow(plot)/10)+
geom_text(aes(label=format(round(mean,2))),hjust=0)+
coord_flip() + theme(axis.line = element_blank(),axis.line.x = element_blank(),
axis.line.y = element_blank(),plot.margin=unit(c(-0.6,1,1,1),"cm"),
panel.background=element_blank(),panel.border=element_blank(),
axis.title.x = element_blank(),axis.title.y = element_blank() )
+ylim(0,max+(0.05*max)) + gghighlight(grepl('Domain',subdomain_name),
unhighlighted_colour = alpha("red",1),
label_key = F))

Related

How to plot counts stackbar in ggplot2 R?

Dataset contains "two friends" and coded "interaction" (all factors). I want to plot the frequency of type of interactions between two friends using a stacked bar. I tried the following code.
Friend1 <- c("A","A","A","A","A","A","A","A","B","B","B","B","B","B","B","B")
Friend2 <- c("1","1","2","2","1","1","2","2","1","1","2","2","1","1","2","2")
Interaction <- c("O","X","D","D","D","X","X","D/R","O","X","D","D","D","X","X","D/R")
df <- data.frame(Friend1, Friend2, Interaction)
df$Friend1 <- as.factor(as.character(df$Friend1))
df$Friend2 <- as.factor(as.character(df$Friend2))
df$Interaction <- as.factor(as.character(df$Interaction))
ggplot(df, aes(fill=Interaction, y=count(Interaction), x=Friend2)) +
geom_bar(position="fill", stat="identity", color = "white") + theme_classic() + theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.background = element_rect(colour = "black", size=1)) + theme(strip.background = element_blank()) + facet_grid(.~Friend1)
Erorr: Error in UseMethod("count") :
no applicable method for 'count' applied to an object of class "character"
How do I "count" these factors to visualize frequency of interactions?
The issue is that dplyr::count expects a dataframe as its first argument and returns a dataframe. However, there is no reason to compute the counts as geom_bar will do that by default, i.e. get rid of y=... and stat="identity":
library(ggplot2)
ggplot(df, aes(fill = Interaction, x = Friend2)) +
geom_bar(position = "fill", color = "white") +
theme_classic() +
theme(
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.background = element_rect(colour = "black", size = 1)
) +
theme(strip.background = element_blank()) +
facet_grid(. ~ Friend1)
An alternative visualization using facets per "friends" column may make your counts clearer than a standard stacked bar:
ggplot(df, aes(x = 1, fill = Interaction)) +
geom_bar(width = 1, color = "white", size = 1, alpha = 0.8) +
geom_text(stat = "count", aes(label = after_stat(count)), size = 7,
position = position_stack(vjust = 0.5), color = "white",
fontface = 2) +
facet_grid(Friend1 ~ Friend2, switch = "both") +
scale_fill_brewer(palette = "Set1") +
coord_polar(theta = "y") +
labs(x = "Friend1", y = "Friend2") +
theme_bw(base_size = 20) +
theme(panel.grid = element_blank(),
strip.background = element_blank(),
strip.placement = "outside",
axis.text.x = element_blank(),
panel.border = element_rect(color = "gray90", fill = NA),
panel.spacing = unit(0, "mm"),
axis.text = element_blank(),
axis.ticks = element_blank())

Multi-row x-axis with separator inside using ggplot

How can I implement histogram with such complex x-axis?
First x-axis row is the week start, second - week end.
Data for tests in csv: https://gofile.io/d/FrhLZh.
What I managed to
hist_data %>%
ggplot(aes(x = week, y = count)) +
geom_col(fill = "#5B879E", width = 0.9, size = 0.7) +
labs(title = "", x = "", y = "") +
theme_bw() + theme_minimal() + theme(legend.position="none")+
theme(
panel.grid.major.x = element_blank(),
panel.grid.minor.x = element_blank(),
panel.grid.major.y = element_blank(),
panel.grid.minor.y = element_blank(),
axis.text.y = element_blank(),
axis.text.x = element_text(vjust = 0.5, size = 8, family = "Inter", colour = "#ffffff"),
axis.line.x = element_blank(),
axis.title.x = element_blank(),
plot.background = element_rect(fill = "#3A464F"),
plot.margin=unit(c(0,0.25,0.5,0), "cm"))+
scale_x_discrete(expand=c(0,0), labels = format(as.Date(hist_data$week_start), "%d-%m"), position = "bottom") +
scale_y_continuous()
Thanks to teunbrand and his ggh4x package, solution:
hist_data %>%
ggplot(aes(x = week, y = count)) +
geom_col(fill = "#5B879E", width = 0.8, size = 0.7)+
labs(title = "", x = "", y = "") +
theme_bw() + theme_minimal() + theme(legend.position="none")+
theme(
panel.grid.major.x = element_blank(),
panel.grid.minor.x = element_blank(),
panel.grid.major.y = element_blank(),
panel.grid.minor.y = element_blank(),
axis.text.y = element_blank(),
axis.text.x = element_text(vjust = 0.5, size = 8, lineheight = 0.8, family = "Inter", colour = "#ffffff"),
axis.line.x = element_blank(),
axis.title.x = element_blank(),
ggh4x.axis.nestline.x = element_line(size = 0.5, colour = "#5B879E", lineend = "square"),
plot.background = element_rect(fill = "#3A464F"),
plot.margin=unit(c(1,0.5,1,0.5), "cm"))+
scale_x_discrete(expand=c(0,0),
labels = paste0(format(as.Date(sort(hist_data$week_start)), "%d.%m"),
"\n", "nonsense", "\n",
format(as.Date(sort(hist_data$week_end)), "%d.%m")), position = "bottom") +
scale_y_continuous() +
guides(x = guide_axis_nested(delim = "nonsense"))
You can add multiple layers of geom_text and geom_segment. Adjust the relative y positions of these layers using a scaling factor.
plotscale <- max(hist_data$count)/50
library(ggplot2)
ggplot(data = hist_data,
aes(x = week_start + floor(week_end-week_start)/2, y = count)) +
geom_col(fill = "#5B879E", width = 4) +
geom_text(aes(y = -6 * plotscale ,
label = format(week_start, "%m-%d")),
color = "#ffffff")+
geom_segment(aes(x = week_start, xend = week_end,
y = -10 * plotscale, yend = -10 * plotscale),
color = "#5B879E", size = 1.5)+
geom_text(aes(y = -14 * plotscale,
label = format(week_end, "%m-%d")),
color = "#ffffff")+
theme_minimal() +
theme(
panel.grid = element_blank(),
axis.text = element_blank(),
axis.title = element_blank(),
plot.background = element_rect(fill = "#3A464F"))+
scale_x_date(expand=c(0,0), date_breaks = "1 week",
labels = NULL)
Consider using ggh4x package for more complex nested x axes.
Raw Data
hist_data <- read.table(text='"","week","count","week_start","week_end"
"1","1",21.5823972708382,2021-01-04,2021-01-10
"2","2",36.122556304552,2021-01-11,2021-01-17
"3","3",34.2809483156697,2021-01-18,2021-01-24
"4","4",25.8546925450454,2021-01-25,2021-01-31
"5","5",29.0309819292706,2021-02-01,2021-02-07
"6","6",33.1503608888827,2021-02-08,2021-02-14
"7","7",27.0490347440184,2021-02-15,2021-02-21
"8","8",30.3031289757874,2021-02-22,2021-02-28
"9","50",32.2876434072602,2020-12-07,2020-12-13
"10","51",33.1939593686481,2020-12-14,2020-12-20
"11","52",26.6853246329896,2020-12-21,2020-12-27
"12","53",23.0715199391151,2020-12-28,2021-01-03', header = TRUE, sep = ",")
hist_data$week_start <- as.Date(hist_data$week_start)
hist_data$week_end <- as.Date(hist_data$week_end)

Modify position and format of percentage labels of donut chart in ggplot2

I have plotted a donut chart with the code below:
library(tidyverse)
library(ggthemes)
df <- data.frame(flavor = c("Chocolate", "Strawberry", "Pistachio"),
per_sold = c(.20, .30, .50))
df %>%
ggplot(aes(x = 2, y = per_sold, fill = flavor)) +
geom_bar(stat = "identity") +
xlim(0.5, 2.5) +
coord_polar(start = 0, theta = "y") +
xlab("") +
ylab("") +
theme(axis.ticks = element_blank(),
axis.text = element_blank(),
axis.title = element_blank(),
panel.grid = element_blank(),
panel.border = element_blank(),
legend.title = element_text(size = rel(2)),
legend.text=element_text(size=rel(1.5))) +
geom_text(aes(label = per_sold), size = 6)
Out:
As you can see, the position of labels are not correct, also I want it show the format of % instead of float number with digit.
How could I modify the code to achive this? Thanks.
All you need is position_stack(vjust = 0.5) and scales::percent:
library(scales)
df %>%
ggplot(aes(x = 2, y = per_sold, fill = flavor)) +
geom_bar(stat = "identity") +
xlim(0.5, 2.5) +
coord_polar(start = 0, theta = "y") +
xlab("") +
ylab("") +
theme(axis.ticks = element_blank(),
axis.text = element_blank(),
axis.title = element_blank(),
panel.grid = element_blank(),
panel.border = element_blank(),
legend.title = element_text(size = rel(2)),
legend.text=element_text(size=rel(1.5))) +
geom_text(aes(label = scales::percent(per_sold)),
size = 6, position = position_stack(vjust = 0.5))

No legend visible in a ggplot set of code although it should be

I have run the following code :`
g <- ggplot(results_table, aes(x = "", y = Pct*100, fill = Criteria),width = 1) +
geom_bar(stat = "identity", color = Palcolor, fill = Palcolor) +
coord_polar(theta = "y", start = 0) +
theme_minimal() +
theme(legend.position = "bottom", legend.title=element_blank(), axis.title.x = element_blank(),,
axis.title.y = element_blank(), panel.border = element_blank(), panel.grid = element_blank(),
axis.text = element_blank(), axis.ticks = element_blank(),
plot.title = element_text(size = 14, hjust = 0.5, vjust = 0)) +
guides(fill = guide_legend(nrow = 4, byrow = TRUE)) +
theme(
legend.key.height = unit(0.3, "lines"), #smaller squares
legend.key.width = unit(0.7, "lines"), #smaller squares
legend.margin=margin(l = 40, unit='pt'),
legend.text = element_text(margin = margin(r = 60, unit = "pt"))) +
xlab("") +
ylab("") +
geom_text(aes(x = 1.70, y = Pct*100/2 + c(0, cumsum(Pct*100)[-length(Pct*100)]),
label = paste0(sprintf("%0.1f", round(Pct*100, digits = 1)),"%")),
size = 3.2) +
labs(title = gTitle)
}`
It created the pie chart as expected, but not the customized legend :
Any idea ?
The problem is that you set the custom color and fill palettes as arguments inside geom_bar. This way no legend will show up. You have to use scale_color/fill_manual to set the color palettes for the color/fill aesthetics.
Using ggplot2::mpg as example data and an example palette from RColorBrewer try this:
library(ggplot2)
library(dplyr)
# Example data
results_table <- mpg %>%
count(class) %>%
mutate(Pct = n / sum(n),
class = reorder(class, Pct)) %>%
rename(Criteria = class) %>%
arrange(desc(Pct)) %>%
mutate()
# Example palette as named vector to get the colors and categories right
Palcolor <- c("2seater" = "#8DD3C7", "minivan" = "#FFFFB3", "pickup" = "#BEBADA", "subcompact" = "#FB8072", "midsize" = "#80B1D3", "compact" = "#FDB462", "suv" = "#B3DE69")
# Example title
gTitle = "Example title"
g <- ggplot(results_table, aes(x = "", y = Pct*100, fill = Criteria),width = 1) +
geom_bar(stat = "identity") +
scale_color_manual(values = Palcolor) +
scale_fill_manual(values = Palcolor) +
coord_polar(theta = "y", start = 0) +
theme_minimal() +
theme(legend.position = "bottom", legend.title=element_blank(), axis.title.x = element_blank(),,
axis.title.y = element_blank(), panel.border = element_blank(), panel.grid = element_blank(),
axis.text = element_blank(), axis.ticks = element_blank(),
plot.title = element_text(size = 14, hjust = 0.5, vjust = 0)) +
guides(fill = guide_legend(nrow = 4, byrow = TRUE)) +
theme(
legend.key.height = unit(0.3, "lines"), #smaller squares
legend.key.width = unit(0.7, "lines"), #smaller squares
legend.margin=margin(l = 40, unit='pt'),
legend.text = element_text(margin = margin(r = 60, unit = "pt"))) +
xlab("") +
ylab("") +
geom_text(aes(x = 1.70, y = Pct*100/2 + c(0, cumsum(Pct*100)[-length(Pct*100)]),
label = paste0(sprintf("%0.1f", round(Pct*100, digits = 1)),"%")),
size = 3.2) +
labs(title = gTitle)
g
Created on 2020-05-16 by the reprex package (v0.3.0)

How to fix "Error: Aesthetics must be either length 1 or the same as the data (28): yintercept"?

I'd like to make a forest plot for my project. Since it is not a typical forest plot built-in any R package, I found the first figure of this page is helpful to my goal, a side table accompanied with the forest plot:
https://mcfromnz.wordpress.com/2012/11/06/forest-plots-in-r-ggplot-with-side-table/
The code which produces that particular figure is pasted below (the original link:https://github.com/nzcoops/blog_code/blob/master/forest_plot.Rmd)
The problem that I ran into is in the "data_table" step. An error pop up when I type the following in R:
data_table
Error: Aesthetics must be either length 1 or the same as the data (28): yintercept
I guess the issue came from geom_hlinein data_table.
After some online search and some try-and-error, I still cannot get rid of that error message and wonder if I can get some help here. Thanks in advance for your help.
--Code that particular produce the first figure:
library(ggplot2)
library(gridExtra)
dat <- data.frame(group = factor(c("A","B","C","D","E","F","G"), levels=c("F","E","D","C","B","A","G")),
cen = c(3.1,2.0,1.6,3.2,3.6,7.6,NA),
low = c(2,0.9,0.8,1.5,2,4.2,NA),
high = c(6,4,2,6,5,14.5,NA))
theme_set(theme_bw())
theme_update(
axis.line = element_line(colour = "black"),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.border = element_blank(),
panel.background = element_blank(),
axis.text.y = element_blank(),
axis.ticks.y = element_blank(),
plot.margin = unit(c(0,0,0,0), "lines"))
p <- ggplot(dat,aes(cen,group)) +
geom_point(size=5, shape=18) +
geom_errorbarh(aes(xmax = high, xmin = low), height = 0.15) +
geom_vline(xintercept = 1, linetype = "longdash") +
scale_x_continuous(breaks = seq(0,14,1), labels = seq(0,14,1)) +
labs(x="Adjusted Odds Ratio", y="")
data_table <- ggplot(lab, aes(x = V05, y = V0, label = format(V1, nsmall = 1))) +
geom_text(size = 4, hjust=0, vjust=0.5) + theme_bw() +
geom_hline(aes(yintercept=c(6.5,7.5))) +
theme(panel.grid.major = element_blank(),
legend.position = "none",
panel.border = element_blank(),
axis.text.x = element_text(colour="white"),#element_blank(),
axis.text.y = element_blank(),
axis.ticks = element_line(colour="white"),#element_blank(),
plot.margin = unit(c(0,0,0,0), "lines")) +
labs(x="",y="") +
coord_cartesian(xlim=c(1,4.5))
lab <- data.frame(V0 = factor(c("A","B","C","D","E","F","G","A","B","C","D","E","F","G","A","B","C","D","E","F","G","A","B","C","D","E","F","G"),, levels=c("G","F","E","D","C","B","A")),
V05 = rep(c(1,2,3,4),each=7),
V1 = c("Occuption","Active","","Inactive","","Inactive","","Recreation","Inactive","","Active","","Inactive","","Gender","Men","Women","Men","Women","Men","Women","OR",3.1,2.0,1.6,3.2,3.6,7.6))
data_table <- ggplot(lab, aes(x = V05, y = V0, label = format(V1, nsmall = 1))) +
geom_text(size = 4, hjust=0, vjust=0.5) + theme_bw() +
geom_hline(aes(yintercept=c(6.5,7.5))) +
theme(panel.grid.major = element_blank(),
legend.position = "none",
panel.border = element_blank(),
axis.text.x = element_text(colour="white"),#element_blank(),
axis.text.y = element_blank(),
axis.ticks = element_line(colour="white"),#element_blank(),
plot.margin = unit(c(0,0,0,0), "lines")) +
labs(x="",y="") +
coord_cartesian(xlim=c(1,4.5))
The easiest fix would be separating geom_hline into 2 different calls
data_table <- ggplot(lab, aes(x = V05, y = V0, label = format(V1, nsmall = 1))) +
geom_text(size = 4, hjust=0, vjust=0.5) + theme_bw() +
geom_hline(aes(yintercept=c(6.5))) +
geom_hline(aes(yintercept=c(7.5))) +
theme(panel.grid.major = element_blank(),
legend.position = "none",
panel.border = element_blank(),
axis.text.x = element_text(colour="white"),#element_blank(),
axis.text.y = element_blank(),
axis.ticks = element_line(colour="white"),#element_blank(),
plot.margin = unit(c(0,0,0,0), "lines")) +
labs(x="",y="") +
coord_cartesian(xlim=c(1,4.5))
data_table
Created on 2018-03-31 by the reprex package (v0.2.0).
You don't need to use aes() with geom_hline (only use aes() if you want a horizontal line for every row of your data.) You can just do:
geom_hline(yintercept = c(6.5, 7.5))
This is explained in the help, see ?geom_hline for more details.

Resources