geom_bar + coord_polar labels with lines - r

I am trying to label the series of concentric circles below with the labels from C in the data frame
I am aware that I could use something like geom_text_repel but I cannot seem to get it to work.
In addition, I cannot seem to get rid of the tick marks on the upper left.
df <- data.frame(C=c(rep("The macro-environment",4),rep("The industry",4),rep("Competitors",4),rep("The organisation",4)))
ggplot(df, aes(factor(1), fill = C)) +
geom_bar(width = 1, colour = NA, show.legend = FALSE, alpha = .8) +
coord_polar() +
labs(
x = "",
y = ""
) +
scale_fill_manual(values = c("#289045", "#beddc7", "#d4dfe9", "#286291")) +
theme(axis.ticks.x = element_blank(),
axis.ticks.y = element_blank()) +
theme_minimal()

A second option would be to add your labels as curved labels using the geomtextpath package:
library(ggplot2)
library(geomtextpath)
ggplot(df, aes(factor(1), fill = C)) +
geom_bar(width = 1, colour = NA, show.legend = FALSE, alpha = .8) +
geom_textpath(aes(x = .5, label = C, group = C),
stat = "count", position = position_stack(vjust = .5),
vjust = 1
) +
coord_polar() +
labs(
x = "",
y = ""
) +
scale_fill_manual(values = c("#289045", "#beddc7", "#d4dfe9", "#286291")) +
theme_void()

You could do:
ggplot(df, aes(factor(1), fill = C)) +
geom_bar(width = 1, colour = NA, show.legend = FALSE, alpha = .8) +
geom_text(stat = 'count', aes(label = C), size = 6,
position = position_stack(vjust = 0.5),
vjust = c(0.5, 0.5, 0.5, 2)) +
coord_polar(start = pi) +
labs(x = NULL, y = NULL ) +
scale_fill_manual(values = c("#289045", "#beddc7", "#d4dfe9", "#286291")) +
theme_void()

Related

How to put 3rd variable on right axis in Horizontal dots plot?

I have horizontal dots plot visualized by Plotly in R.
My data set contains 3 numerical and 1 categorical variable.
'origin' is on y-axis. 'change' and 'rate' variables are visualized into circles. Now I want to put 'Percentage' variable on right axis in the circles
df <- data.frame (origin = c("A","B","C","D","E","F","G","H","I","J"),
Percentage = c(23,16,32,71,3,60,15,21,44,60),
rate = c(10,12,20,200,-25,12,13,90,-105,23),
change = c(10,12,-5,12,6,8,0.5,-2,5,-2))
library(ggplot2)
ggplot(df, aes(x = rate, y = factor(origin, rev(origin)))) +
geom_hline(aes(yintercept = origin), color = 'gray') +
geom_vline(xintercept = 0, linetype = 2, color = 'gray') +
geom_point(aes(color = 'Rate'), size = 10) +
geom_text(aes(label = rate), color = 'white') +
geom_point(aes(x = change, color = 'Change'), size = 10) +
geom_text(aes(label = change, x = change)) +
theme_minimal(base_size = 16) +
scale_x_continuous(labels = ~paste0(.x, '%'), name = NULL) +
scale_color_manual(values = c('#aac7c4', '#5f9299')) +
theme(panel.grid = element_blank(),
axis.text.y = element_text(color = 'gray50')) +
labs(color = NULL, y = NULL)
Output:
Expected Output:
You could do
ggplot(df, aes(x = rate, y = factor(origin, rev(origin)))) +
geom_hline(aes(yintercept = origin), color = 'gray') +
geom_vline(xintercept = 0, linetype = 2, color = 'gray') +
geom_point(aes(color = 'Rate'), size = 10) +
geom_text(aes(label = rate), color = 'white') +
geom_point(aes(x = change, color = 'Change'), size = 10) +
geom_text(aes(label = change, x = change)) +
geom_point(aes(x = 220, fill = "Percentage"), color = "blue",
size = 12, shape = 21) +
geom_text(aes(x = 220, label = paste0(Percentage, "%"))) +
theme_minimal(base_size = 16) +
scale_x_continuous(labels = ~paste0(.x, '%'), name = NULL) +
scale_color_manual(values = c('#aac7c4', '#5f9299')) +
scale_fill_manual(values = "white", name = NULL) +
theme(panel.grid = element_blank(),
axis.text.y = element_text(color = 'gray50')) +
coord_cartesian(xlim = c(-120, 230), ylim = c(0, 11),
expand = FALSE) +
labs(color = NULL, y = NULL)

How do I neatly align my stacked barchart labels, with differing alignments to each side of the bar?

I have my labels roughly aligned to each side of my stacked bar chart. The problem is that they look like a mess because they aren't right and left justified on either side of the bar. How do I fix this so that they look professional?
df3 <- data.frame(
Label = c("Dasher", "Dancer", "Comet", "Cupid", "Prancer", "Blitzen", "Rudolph"),
Amount = c(650.01, 601.01, 340.05, 330.20, 260.01, 250.80, 10.10)
)
# Sort order
level_order <- df3 %>%
arrange(desc(Amount))
ggplot(level_order, aes(fill=fct_inorder(Label), y=Amount, x="")) +
geom_bar(position="stack", stat="identity", width = 0.55) +
scale_fill_brewer(palette = "Blues", direction = -1) +
theme_void() +
geom_text(aes(label = paste0("$", Amount)),
position = position_stack(vjust = 0.5),
hjust = -3.1,
size = 5) +
geom_text(aes(label = Label),
position = position_stack(vjust = 0.5),
hjust = 5,
size = 5) +
theme(legend.position = "none") +
theme(plot.title = element_text(size = 50, hjust = .5, vjust = 0)) +
ggtitle("Food Costs by Reindeer")
hjust determines the text alignment (with 0 being left-aligned, and 1 right-aligned). The x co-ordinate of your geom_text at the moment is defaulted to 1, so changing this will change the position of the text.
ggplot(level_order, aes(fill=fct_inorder(Label), y=Amount, x="")) +
geom_bar(position="stack", stat="identity", width = 0.55) +
scale_fill_brewer(palette = "Blues", direction = -1) +
theme_void() +
geom_text(aes(x=0.6, label = paste0("$", Amount)),
position = position_stack(vjust = 0.5),
hjust = 0.5,
size = 5) +
geom_text(aes(x=1.4, label = Label),
position = position_stack(vjust = 0.5),
hjust = 0.5,
size = 5) +
theme(legend.position = "none") +
theme(plot.title = element_text(size = 50, hjust = .5, vjust = 0)) +
ggtitle("Food Costs by Reindeer")
You can also pass hjust as an aesthetic. In order to do that, you will need to prepare the labelling as a separate data frame. Then, you only need to call geom_text once. I don't say this is necessarily better, but just pointing out that this is possible. A few more comments in the code, also regarding a few common pitfalls.
library(tidyverse)
df3 <- data.frame(
Label = c("Dasher", "Dancer", "Comet", "Cupid", "Prancer", "Blitzen", "Rudolph"),
Amount = c(650.01, 601.01, 340.05, 330.20, 260.01, 250.80, 10.10)
) %>%
## arrange step here
arrange(desc(Amount))
## I like to prepare the data outside ggplot
label_df <- df3 %>%
mutate(Amount_lab = paste0("$", Amount)) %>%
pivot_longer(-Amount) %>%
## this adds a column for your adjustment, and the x position compared with the central column
mutate(hjust = rep(0:1, nrow(.)/2),
x = rep(c(1.21, .79), nrow(.)/2))
ggplot(mapping = aes(y = Amount)) +
## geom_col is geom_bar(stat = "identity"), stack is default, so you can omit it
## call data in the geom layers
## set x to 1
## width = .4 so it matches your selected x from above
geom_col(data = df3, aes(x = 1, fill=fct_inorder(Label)), width = .4) +
scale_fill_brewer(palette = "Blues", direction = -1) +
## need to reverse both y and value, weirdly
geom_text(data = label_df, aes(x, y = rev(Amount), label = rev(value),
## this is the main trick
hjust = hjust),
position = position_stack(vjust = 0.5) ) +
## sadly, need to turn clip off
coord_cartesian(clip = "off") +
theme_void() +
## call theme only once!!
theme(legend.position = "none",
plot.title = element_text(size = 20, hjust = .5, vjust = 0),
## you need to add a margin
plot.margin = margin(r = .6, l = .6, unit = "in")) +
ggtitle("Food Costs by Reindeer")
Created on 2021-12-20 by the reprex package (v2.0.1)
Try fixing the x co-ordinate in the call to geom_text and managing alignment with hjust...
df3 <- data.frame(
Label = c("Dasher", "Dancer", "Comet", "Cupid", "Prancer", "Blitzen", "Rudolph"),
Amount = c(650.01, 601.01, 340.05, 330.20, 260.01, 250.80, 10.10)
)
library(ggplot2)
library(dplyr)
library(forcats)
level_order <- df3 %>%
arrange(desc(Amount))
ggplot(level_order, aes(fill=fct_inorder(Label), y=Amount, x="")) +
geom_bar(position="stack", stat="identity", width = 0.55) +
scale_fill_brewer(palette = "Blues", direction = -1) +
theme_void() +
geom_text(aes(x = 1.3, label = paste0("$", Amount)),
position = position_stack(vjust = 0.5),
hjust = 0,
size = 5) +
geom_text(aes(x = 0.6, label = Label),
position = position_stack(vjust = 0.5),
hjust = 0,
size = 5) +
theme(legend.position = "none") +
theme(plot.title = element_text(size = 50, hjust = .5, vjust = 0)) +
ggtitle("Food Costs by Reindeer")
Created on 2021-12-19 by the reprex package (v2.0.1)
Using Peter's answer above (reminding me of the "x" position argument I forgot existed), this was the final fix that got what I was looking for. hjust = 0 is left-justification and hjust = 1 is right justification.
library(tidyverse)
library(grid)
df3 <- data.frame(
Label = c("Dasher", "Dancer", "Comet", "Cupid", "Prancer", "Blitzen", "Rudolph"),
Amount = c(650.01, 601.01, 340.05, 330.20, 260.01, 250.80, 10.10)
)
# Sort order
level_order <- df3 %>%
arrange(desc(Amount))
ggplot(level_order, aes(fill=fct_inorder(Label), y=Amount, x="")) +
geom_bar(position="stack", stat="identity", width = 0.55) +
scale_fill_brewer(palette = "Blues", direction = -1) +
theme_void() +
geom_text(aes(x = 1.3, label = paste0("$", Amount)),
position = position_stack(vjust = 0.5),
hjust = 0,
size = 5) +
geom_text(aes(x = 0.7, label = Label),
position = position_stack(vjust = 0.5),
hjust = 1,
size = 5) +
theme(legend.position = "none",
plot.margin = unit(c(0,0,2,0), "cm"))
grid.text("Food Costs by Reindeer", x = unit(0.5, "npc"), y = unit(0, "npc"),
vjust = -0.5, gp = gpar(cex=4))

Overlapping text on top of geom_bar in ggplot2

I have made a barplot similar to the one below using ggplot2.
I cannot get the percentages on top of the bars to be centered and not overlapping of other bars and numbers. Sample code is below.
library(tidyverse)
cat1=c("cat1","cat1","cat1","cat1","cat1","cat1","cat1","cat1","cat1","cat1","cat1","cat1",
"cat2","cat2","cat2","cat2","cat2","cat2","cat2","cat2","cat2","cat2","cat2","cat2",
"cat3","cat3","cat3","cat3","cat3","cat3","cat3","cat3","cat3","cat3","cat3","cat3",
"cat4","cat4","cat4","cat4","cat4","cat4","cat4","cat4","cat4","cat4","cat4","cat4")
cat2=c("c1","c2","c3","c4","c5","c6","c7","c8","c9","c10","c11","c12",
"c1","c2","c3","c4","c5","c6","c7","c8","c9","c10","c11","c12",
"c1","c2","c3","c4","c5","c6","c7","c8","c9","c10","c11","c12",
"c1","c2","c3","c4","c5","c6","c7","c8","c9","c10","c11","c12")
count1=round(rnorm(48,10))
fakeperc=rnorm(48,9)
df1=cbind(count1,fakeperc)
df2=cbind(cat1,cat2)
finaldf=as.data.frame(cbind(df1,df2))
finaldf$cat1=as.factor(finaldf$cat1)
finaldf$fakeperc=as.numeric(finaldf$fakeperc)
#finaldf$cat1=factor(finaldf$cat1,levels = c("cat1","cat2","cat3","cat4"))
finaldf$cat2 = factor(finaldf$cat2,
levels = c("c1","c2","c3","c4","c5","c6","c7","c8","c9","c10","c11","c12"))
a=ggplot(data=finaldf,aes(x=cat1, y=count1,
fill=cat2,group=cat2)) +
geom_bar(stat='identity',color='black',width=.65,position=position_dodge(width=.9))+
scale_y_discrete(limits=0:50,breaks=c(0,10,20,30,40,50))+
scale_fill_brewer(palette="Set3") +
theme_classic() +
geom_text(data = finaldf,
aes(x=cat1,y=count1,group=cat2,
label=format(paste(round(fakeperc),"%",sep = ""))),inherit.aes = F,
color='black',position=position_dodge(.9),vjust=-.5,size=3)
a
When trying to add either nudge_y or nudge_x to the geom_text call, nothing happens. I suspect this is because there is already a position_dodge call. I am open any and all solutions to make these percentages non-overlapping and legible.
What do you think of this?
# I think you meant count1 to be numeric
finaldf$count1 <- as.numeric(finaldf$count1)
ggplot(data = finaldf,
aes(x = cat1,
y = count1,
fill = cat2,
group = cat2)) +
geom_col(color = 'black',
width = 0.65,
position = position_dodge(width = 0.9)) +
geom_text(data = finaldf,
aes(x = cat1,
y = count1,
group = cat2,
label = scales::percent(fakeperc/100, accuracy = 0.01)),
inherit.aes = FALSE,
color = 'black',
position = position_dodge(0.9),
hjust = -0.1,
size = 3) +
scale_y_continuous(limits = c(0,50), breaks = c(0,10,20,30,40,50)) +
scale_fill_brewer(palette = "Set3") +
theme_classic() +
coord_flip()
I cleaned up a bit the code (according to my taste)
I changed scale_y_numeric to scale_y_continuous (since count1 should be numeric)
I used coord_flip() to make it more readable
I used scales::percent to write percentage numbers
(don't know why you set up limits from 0 to 50 but I left them as I suppposed they were intended)
If you don't want to use coor_flip:
finaldf$count1 <- as.numeric(finaldf$count1)
ggplot(data = finaldf,
aes(x = cat1,
y = count1,
fill = cat2,
group = cat2)) +
geom_col(color = 'black',
width = 0.65,
position = position_dodge(width = 0.9)) +
geom_text(data = finaldf,
aes(x = cat1,
y = count1,
group = cat2,
label = scales::percent(fakeperc/100, accuracy = 0.01)),
inherit.aes = FALSE,
color = 'black',
position = position_dodge(0.9),
hjust = -0.1,
angle = 90,
size = 3) +
scale_y_continuous(limits = c(0,50), breaks = c(0,10,20,30,40,50)) +
scale_fill_brewer(palette = "Set3") +
theme_classic()
Is this what you are looking for:
library(ggplot2)
#Code
ggplot(data=finaldf,aes(x=cat2, y=count1,
fill=cat2,group=cat2)) +
geom_bar(stat='identity',color='black',
position=position_dodge(width=1))+
scale_fill_brewer(palette="Set3") +
theme_bw() +
geom_text(aes(x=cat2,y=count1,group=cat2,
label=format(paste(round(fakeperc),"%",sep = ""))),inherit.aes = F,
color='black',position=position_dodge(1),
size=3,vjust=-0.5)+
facet_wrap(.~cat1,scales = 'free_x',nrow = 1,strip.position = 'bottom')+
theme(axis.text.x = element_blank(),
axis.ticks.x = element_blank(),
legend.position = 'top',
strip.background = element_blank(),
panel.spacing = unit(2, "lines"),
panel.grid = element_blank())+
guides(fill = guide_legend(nrow = 1))
Output:

Avoid applying alpha aesthetic to geom_text in ggplot2

I have the following ggplot2 chart. I don't want transparency on the value labels.
Code:
ggplot(test, aes(x = reorder(org, -as.numeric(level)), y = obsAvg, fill = level, alpha = round)) +
geom_bar(stat = "identity", position = "dodge") +
scale_fill_manual(values = c("#E69F00", "#56B4E9", "#009E73")) +
scale_alpha_manual(values = c(.5, .75, 1), guide = FALSE) +
labs(title = "Average Observation Score by Round", y = "", x = "", fill = "Group") +
theme_bw() +
geom_text(aes(label = round(obsAvg,1)), vjust = -.5, size = 4, fontface="bold", position = position_dodge(width = .9)) +
scale_y_continuous(limits = c(0,4), expand = c(0,0)) +
theme(legend.position="bottom")
Data:
set.seed(1)
test <- data.frame(
org = rep(c("Mammals", "Cats", "Tigers", "Lions", "Cheetahs"), 3),
level = rep(c("Animals", "Family", rep("Species", 3)), 3),
group = rep("Cats",15),
round = rep(c("Round1", "Round2", "Round3"),5),
obsAvg = runif(15, 1, 4)
)
I have tried moving the alpha = round to be an aesthetic of geom_bar() but then I lose the dodge of the labels:
How can I replicate the top chart but not apply the transparency aesthetic to my labels?
I would move the aes(alpha=) to geom_bar and then add an aes(group=) to geom_text to recover the dodging.
ggplot(test, aes(x = reorder(org, -as.numeric(level)), y = obsAvg, fill = level)) +
geom_bar(aes(alpha=round), stat = "identity", position = "dodge") +
scale_fill_manual(values = c("#E69F00", "#56B4E9", "#009E73")) +
scale_alpha_manual(values = c(.5, .75, 1), guide = FALSE) +
labs(title = "Average Observation Score by Round", y = "", x = "", fill = "Group") +
theme_bw() +
geom_text(aes(label = round(obsAvg,1), group=round), vjust = -.5, size = 4, fontface="bold", position = position_dodge(width = .9)) +
scale_y_continuous(limits = c(0,4), expand = c(0,0)) +
theme(legend.position="bottom")
That's a pretty plot.

Add legend to manually added lines using ggplot

I'm trying to add the corresponding legend for 3 manually added lines using ggplot. My code is the following:
library(ggplot2)
df = data.frame(error = c(0.0832544999, 0.0226680026, 0.0082536264, 0.0049199958, 0.0003917755, 0.0003859976, 0.0003888253, 0.0003953918, 0.0003958398), sDev = c(8.188111e-03, 2.976161e-03, 1.466221e-03, 2.141425e-03, 2.126976e-05, 2.139364e-05, 2.169059e-05, 2.629895e-05, 2.745938e-05))
minimum <- 6
best.model <- 5
gplot <- ggplot(df, aes(x=1:length(error), y=error)) +
scale_x_continuous(breaks = seq_along(df$error)) +
geom_point(size = 3) +
geom_line() +
geom_errorbar(data = df, aes(x = 1:length(error), ymin = error - sDev, ymax = error + sDev),
width = 0.1) +
geom_hline(data = df, aes(yintercept = error[minimum] + sDev[minimum]), linetype = "dashed") +
geom_vline(xintercept = minimum, linetype = "dotted", color = "red", size = 1) +
geom_vline(xintercept = best.model, linetype = "dotted", color = "blue", size = 1) +
theme_gray(base_size = 18) +
theme(axis.text = element_text(color = "black")) +
labs(x = "# of parameters", fontface = "bold") +
labs(y = "CV error") +
labs(title = "Cross-validation error curve")
I'd like to know how to add the legends for the 3 dotted lines in black, red, and blue.
Thanks a lot in advance!
The trick is to use appropriate mapping:
gplot <- ggplot(df, aes(x=1:length(error), y=error)) +
scale_x_continuous(breaks = seq_along(df$error)) +
geom_point(size = 3) +
geom_line() +
geom_errorbar(data = df, aes(x = 1:length(error), ymin = error - sDev, ymax = error + sDev),
width = 0.1) +
geom_hline(data = df, aes(yintercept = error[minimum] + sDev[minimum], linetype="a", colour="a")) +
geom_vline(data= data.frame(type="b", col="b", minimum=minimum),
aes(linetype=type, colour=col, xintercept = minimum), size = 1, show_guide = TRUE) +
geom_vline(data= data.frame(type="b", col="b", best.model=best.model),
aes(linetype="c", colour="c", xintercept = best.model), size = 1, show_guide = TRUE) +
scale_colour_manual(name="Legend", values = c("a" = "black", "b" = "red", "c" = "blue")) +
scale_linetype_manual(name="Legend", values = c("a" = "dashed", "b" = "dotted", "c" = "dotted")) +
theme_gray(base_size = 18) +
theme(axis.text = element_text(color = "black"),
legend.key.height = grid::unit(0.1, "npc")) +
labs(x = "# of parameters", fontface = "bold") +
labs(y = "CV error") +
labs(title = "Cross-validation error curve")

Resources