Control colour of geom_text_repel - r

I would like to change the colour of one of my ggrepel labels to black. I have tried to override the inheritance by specifying ...geom_text_repel(...colour='black') but that doesn't seem to work.
My attempt at a fix to the problem is in the second geom_text_repel function (below).
N.B. If there is a way to control the colour of individual geom_text_repel elements, rather than having to call the function twice, I would prefer that.
library("tidyverse")
library("ggthemes")
library("ggrepel")
df1 <- gather(economics, variable_name, observation, -date) %>%
rename(period = date) %>%
filter(variable_name == 'psavert')
df2 <- gather(economics, variable_name, observation, -date) %>%
rename(period = date) %>%
filter(variable_name == 'uempmed')
ggplot(df1, aes(x = period, y = observation, colour = variable_name)) +
geom_line() +
geom_line(data = df2, colour = 'black', size = .8) +
geom_text_repel(
data = subset(df1, period == max(as.Date(period, "%Y-%m-%d"))),
aes(label = variable_name),
size = 3,
nudge_x = 45,
segment.color = 'grey80'
) +
geom_text_repel(
data = subset(df2, period == max(as.Date(period, "%Y-%m-%d"))),
aes(label = variable_name, colour = 'black'), #How do I set the colour of the label text to black?
size = 3,
nudge_x = 45,
segment.color = 'grey80'
) +
scale_y_continuous(labels = scales::comma) +
theme_minimal(base_size = 16) +
scale_color_tableau() +
scale_fill_tableau() +
theme(legend.position = 'none') +
labs(x="", y="", title = "Economic Data") +
scale_x_date(limits = c(min(df1$period), max(df1$period) + 1200))

Do the same thing you did in your geom_line() layer. You want to set a color, not a mapping. Make colour = 'black' an argument to geom_text_repel(), not aes().
ggplot(df1, aes(x = period, y = observation, colour = variable_name)) +
geom_line() +
geom_line(data = df2, colour = 'black', size = .8) + # just like this layer
geom_text_repel(
data = subset(df1, period == max(as.Date(period, "%Y-%m-%d"))),
aes(label = variable_name),
size = 3,
nudge_x = 45,
segment.color = 'grey80'
) +
geom_text_repel(
data = subset(df2, period == max(as.Date(period, "%Y-%m-%d"))),
aes(label = variable_name) # don't assign it here,
size = 3,
nudge_x = 45,
segment.color = 'grey80',
colour = "black" # assign it here
) +
scale_y_continuous(labels = scales::comma) +
theme_minimal(base_size = 16) +
scale_color_tableau() +
scale_fill_tableau() +
theme(legend.position = 'none') +
labs(x="", y="", title = "Economic Data") +
scale_x_date(limits = c(min(df1$period), max(df1$period) + 1200))
Note that now the first line AND text are now both set manually to "black", so the automatic variable assignment will start over with next line (and text). If you want to set that manually to a different color, you can use the same strategy (set it as an argument to the geom, not as an argument to aes

Related

How to hide information on graph from the Legend in ggplotly?

I have horizontal dots plot replotted via ggplotly
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)
plt <- 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)
ggplotly(plt)
The only issue is that when I hide one of the dot from the figure, texts are still appeared (see below), so is there way to tackle this issue and hide text with circle by clicking on legend?
P.S
(setting text colour in white color = 'white' is not option for me)
You can use the fill aesthetic for the points (as long as they are shape = 21) and use the color aesthetic for the text. As long as these have the same labels for aesthetic mapping, the interactivity for both points and text will be linked.
One minor annoyance is that this changes the plotly legend labels, even though they are correct in the ggplot version. This requires a little direct manipulation of the plotly object itself:
plt <- ggplot(df, aes(x = rate, y = factor(origin, rev(origin)))) +
geom_segment(aes(x = -100, xend = 200,
y = origin, yend = origin), color = 'gray') +
geom_vline(xintercept = 0, linetype = 2, color = 'gray') +
geom_point(aes(fill = 'Rate'), shape = 21, size = 10, color = NA) +
geom_text(aes(label = rate, color = 'Rate')) +
geom_point(aes(x = change, fill = 'Change'),
color = NA, shape = 21, size = 10) +
geom_text(aes(label = change, x = change, color = "Change")) +
theme_minimal(base_size = 16) +
scale_x_continuous(labels = ~paste0(.x, '%'), name = NULL) +
scale_fill_manual(values = c('#aac7c4', '#5f9299')) +
scale_color_manual(values = c("black", "white")) +
theme(panel.grid = element_blank(),
axis.text.y = element_text(color = 'gray50')) +
labs(color = NULL, y = NULL, fill = NULL)
p <- ggplotly(plt)
p$x$data[[3]]$name <- p$x$data[[3]]$legendgroup <-
p$x$data[[4]]$name <- p$x$data[[4]]$legendgroup <- "Rate"
p$x$data[[5]]$name <- p$x$data[[5]]$legendgroup <-
p$x$data[[6]]$name <- p$x$data[[6]]$legendgroup <- "Change"
p
This gives us the following plot:
Now clicking on Rate we get:
And clicking on Change we get

How to automatically change label color depending on relative values (maximum/minimum)?

In order to make a dynamic visualization, for example in a dashboard, I want to display the label colors (percentages or totals) depending on their real values in black or white.
As you can see from my reprex below, I changed the color of the label with the highest percentage manually to black, in order gain a better visability.
Is there a was, to automatically implement the label color? The label with the highest percentage corresponding should always be black, if data is changing over time.
library(ggplot2)
library(dplyr)
set.seed(3)
reviews <- data.frame(review_star = as.character(sample.int(5,400, replace = TRUE)),
stars = 1)
df <- reviews %>%
group_by(review_star) %>%
count() %>%
ungroup() %>%
mutate(perc = `n` / sum(`n`)) %>%
arrange(perc) %>%
mutate(labels = scales::percent(perc))
ggplot(df, aes(x = "", y = perc, fill = review_star)) +
geom_col(color = "black") +
geom_label(aes(label = labels), color = c( "white", "white","white",1,"white"),
position = position_stack(vjust = 0.5),
show.legend = FALSE) +
guides(fill = guide_legend(title = "Answer")) +
scale_fill_viridis_d() +
coord_polar(theta = "y") +
theme_void()
you can set the colors using replace(rep('white', nrow(df)), which.max(df$perc), 'black').
ggplot(df, aes(x = "", y = perc, fill = review_star)) +
geom_col(color = "black") +
geom_label(aes(label = labels),
color = replace(rep('white', nrow(df)), which.max(df$perc), 'black'),
position = position_stack(vjust = 0.5),
show.legend = FALSE) +
guides(fill = guide_legend(title = "Answer")) +
scale_fill_viridis_d() +
coord_polar(theta = "y") +
theme_void()

Add legends to ggplot2

I am trying to add legend on ggplot2.
When I use the following codes, I get the following plot.
ggplot() +
geom_bar(data = profitCountries, aes(y = (revenue), x = residence), stat="identity",
fill="darkgreen", color = "black") +
geom_bar(data = profitCountries, aes(y = -(total_spend), x = residence), stat="identity",
fill="red", color = "black") +
geom_line(data = profitCountries, aes(y = total_profit, x = residence, group = 1), size = 1.5,
color = "blue" ) +
scale_y_continuous(breaks = seq(-500000,500000,100000), limits=c(-500000, 500000) ) +
xlab('Countries') + ggtitle('Campaign spending and revenue by countries') +
ylab('Campaign spending Revenue') + theme_grey()
As suggested in other posts, I added color inside aes(). When I try to do that using the following code, I get the following plot.
ggplot() +
geom_bar(data = profitCountries, aes(y = (revenue), x = residence, fill="darkgreen"), stat="identity",
color = "black") +
geom_bar(data = profitCountries, aes(y = -(total_spend), x = residence, fill="red"), stat="identity",
color = "black") +
geom_line(data = profitCountries, aes(y = total_profit, x = residence, group = 1, color = "blue"),
size = 2 ) +
scale_y_continuous(breaks = seq(-500000,500000,100000), limits=c(-500000, 500000) ) +
xlab('Countries') + ggtitle('Campaign spending and revenue by countries') +
ylab('Campaign spending Revenue') + theme_grey()
In the second plot, the colors change and two legends are created. Is there anyway to solve this?
You are currently mapping the character vector green to a manual scale whose colors are automatically determined.
You probably want
ggplot(profitCountries, aes(residence)) +
geom_bar(aes(y = (revenue), fill="Revenue"), stat="identity",
color = "black") +
geom_bar(aes(y = -(total_spend), fill="Campaign Spending"), stat="identity",
color = "black") +
geom_line(aes(y = total_profit, group = 1, color = "Net"), size = 2) +
scale_y_continuous(breaks = seq(-500000,500000,100000), limits=c(-500000, 500000) ) +
xlab('Countries') +
ggtitle('Campaign spending and revenue by countries') +
ylab('Campaign spending Revenue') +
theme_grey() +
scale_fill_manual(values = c("Revenue" = "darkgreen", "Campaign Spending" = "red")) +
scale_color_manual(values = c("Net" = "blue"))

Aligning ggplot labels

I have a dataset where I would compare some new and old changes within some groups (Species). I have a plot which creates the desired output, but the labels are not as desired. I would like them to be between the old and new bars. This is a bit tricky when the labels are of different length.
Example
library(ggplot2)
iris$change <- sample(c('new', 'old'), 150, replace = TRUE)
iris$mean1 <- ifelse(iris$Sepal.Length < mean(iris$Sepal.Length), 'Below', 'Above')
breaks
breaks <- unique(paste(iris$Species[iris$change == 'new'], iris$change[iris$change == 'new']))
ggplot(iris, aes(x = paste(Species, change), y = Petal.Width, fill = mean1)) +
geom_bar(stat = 'identity', position = 'fill') +
scale_x_discrete(breaks = breaks, labels = c('Setosa', 'vers', 'Virginica')) +
theme(axis.text.x = element_text(hjust = -1.2)) +
geom_text(aes(label = ifelse(change == "new", 'new', '')), size = 3, y = 0.05) +
geom_text(aes(label = ifelse(change == "old", 'old', '')), size = 3, y = 0.05)
I believe you can get what you want using faceting:
library(ggplot2)
iris$change <- sample(c('new', 'old'), 150, replace = TRUE)
iris$mean1 <- ifelse(iris$Sepal.Length < mean(iris$Sepal.Length), 'Below', 'Above')
ggplot(iris, aes(x = change, y = Petal.Width, fill = mean1)) +
geom_bar(stat = 'identity', position = 'fill') +
facet_wrap(~Species, strip.position = "bottom")+
theme(strip.placement = "outside",
strip.background = element_rect(colour = "white", fill = "white"))+
xlab(NULL)

Aesthetics must be either length 1 or the same as the data (1): x, y, label

I'm working on some data on party polarization (something like this) and used geom_dumbbell from ggalt and ggplot2. I keep getting the same aes error and other solutions in the forum did not address this as effectively. This is my sample data.
df <- data_frame(policy=c("Not enough restrictions on gun ownership", "Climate change is an immediate threat", "Abortion should be illegal"),
Democrats=c(0.54, 0.82, 0.30),
Republicans=c(0.23, 0.38, 0.40),
diff=sprintf("+%d", as.integer((Democrats-Republicans)*100)))
I wanted to keep order of the plot, so converted policy to factor and wanted % to be shown only on the first line.
df <- arrange(df, desc(diff))
df$policy <- factor(df$policy, levels=rev(df$policy))
percent_first <- function(x) {
x <- sprintf("%d%%", round(x*100))
x[2:length(x)] <- sub("%$", "", x[2:length(x)])
x
}
Then I used ggplot that rendered something close to what I wanted.
gg2 <- ggplot()
gg2 <- gg + geom_segment(data = df, aes(y=country, yend=country, x=0, xend=1), color = "#b2b2b2", size = 0.15)
# making the dumbbell
gg2 <- gg + geom_dumbbell(data=df, aes(y=country, x=Democrats, xend=Republicans),
size=1.5, color = "#B2B2B2", point.size.l=3, point.size.r=3,
point.color.l = "#9FB059", point.color.r = "#EDAE52")
I then wanted the dumbbell to read Democrat and Republican on top to label the two points (like this). This is where I get the error.
gg2 <- gg + geom_text(data=filter(df, country=="Government will not control gun violence"),
aes(x=Democrats, y=country, label="Democrats"),
color="#9fb059", size=3, vjust=-2, fontface="bold", family="Calibri")
gg2 <- gg + geom_text(data=filter(df, country=="Government will not control gun violence"),
aes(x=Republicans, y=country, label="Republicans"),
color="#edae52", size=3, vjust=-2, fontface="bold", family="Calibri")
Any thoughts on what I might be doing wrong?
I think it would be easier to build your own "dumbbells" with geom_segment() and geom_point(). Working with your df and changing the variable refences "country" to "policy":
library(tidyverse)
# gather data into long form to make ggplot happy
df2 <- gather(df,"party", "value", Democrats:Republicans)
ggplot(data = df2, aes(y = policy, x = value, color = party)) +
# our dumbell
geom_path(aes(group = policy), color = "#b2b2b2", size = 2) +
geom_point(size = 7, show.legend = FALSE) +
# the text labels
geom_text(aes(label = party), vjust = -1.5) + # use vjust to shift text up to no overlap
scale_color_manual(values = c("Democrats" = "blue", "Republicans" = "red")) + # named vector to map colors to values in df2
scale_x_continuous(limits = c(0,1), labels = scales::percent) # use library(scales) nice math instead of pasting
Produces this plot:
Which has some overlapping labels. I think you could avoid that if you use just the first letter of party like this:
ggplot(data = df2, aes(y = policy, x = value, color = party)) +
geom_path(aes(group = policy), color = "#b2b2b2", size = 2) +
geom_point(size = 7, show.legend = FALSE) +
geom_text(aes(label = gsub("^(\\D).*", "\\1", party)), vjust = -1.5) + # just the first letter instead
scale_color_manual(values = c("Democrats" = "blue", "Republicans" = "red"),
guide = "none") +
scale_x_continuous(limits = c(0,1), labels = scales::percent)
Only label the top issue with names:
ggplot(data = df2, aes(y = policy, x = value, color = party)) +
geom_path(aes(group = policy), color = "#b2b2b2", size = 2) +
geom_point(size = 7, show.legend = FALSE) +
geom_text(data = filter(df2, policy == "Not enough restrictions on gun ownership"),
aes(label = party), vjust = -1.5) +
scale_color_manual(values = c("Democrats" = "blue", "Republicans" = "red")) +
scale_x_continuous(limits = c(0,1), labels = scales::percent)

Resources