R - Plotly several color palettes grouped bar - r

I have the following plot with plotly :
library(plotly)
library(dplyr)
ggplot2::diamonds %>% count(cut, clarity) %>%
plot_ly(x = ~cut, y = ~n, color = ~clarity,colors = 'Blues')
Right now I only have one color palette 'Blues' for all groups. How can i customize it so I have one color palette per group ?
For example, I would like the color palette
'Blues' for the level 'Fair'
'Greens' for the level 'Good'
'Reds' for the level 'Very Good'
'Purples' for the level 'Premium'
'Greys' for the level 'Ideal'

The following code seems to work with a static ggplot2 plot:
library(tidyverse)
library(plotly)
library(RColorBrewer)
sPalette <- c("Blues", "Greens", "Reds", "Purples", "Greys") %>%
sapply(., function(x) brewer.pal(8, name = x)) %>%
as.vector
diamonds %>%
count(cut, clarity) %>%
ggplot(., aes(x = cut, y = n, fill = interaction(clarity, cut, sep = " - "))) +
geom_bar(stat = "identity", position = "dodge") +
scale_fill_manual(values = sPalette, guide = F) +
theme_minimal()
This is the result:
The corresponding plot_ly code produces bars which have a wide space between them, and I'm not exactly sure why that's the case:
diamonds %>%
count(cut, clarity) %>%
plot_ly(x = ~cut, y = ~n, color = ~interaction(clarity, cut, sep = " - ") , colors = sPalette)
It turns out however, that ggplotly does work:
p <- diamonds %>%
count(cut, clarity) %>%
ggplot(., aes(x = cut, y = n, fill = interaction(clarity, cut, sep = " - "))) +
geom_bar(stat = "identity", position = "dodge") +
scale_fill_manual(values = sPalette, guide = F) +
theme_minimal()
ggplotly(p)

Related

Placing data labels for stacked bar chart at top of bar

I have been attempting to add a label on top of each bar to represent the proportion that each ethnic group makes up in referrals.
For some reason I cannot get the labels to be placed at the top of each bar. How do I fix this?
My code below
freq <- df %>%
group_by(ethnicity) %>%
summarise(n = n()) %>%
mutate(f = round((n/sum(n)*100, 1))
df %>%
group_by(pathway) %>%
count(ethnicity) %>%
ggplot(aes(x = ethnicity, y = n , fill = pathway)) +
geom_bar(stat = "identity", position = "stack") +
geom_text(data = freq,
aes(x= ethnicity, y = f, label = f),
inherit.aes = FALSE) +
theme(legend.position = "bottom") +
scale_fill_manual(name = "",
values = c("light blue", "deepskyblue4"),
labels = "a", "b") +
xlab("") +
ylab("Number of Referrals") +
scale_y_continuous(breaks = seq(0, 2250, 250), expand = c(0,0)
Here is what it currently looks like
Since you are using the count as your y-axis position in geom_bar, you need to use the same thing in your geom_text to get the labels in the right place. Below is an example using mtcars dataset. Using vjust = -1 I put a little bit of space between the label and the bars to make it more legible and aesthetically pleasing.
library(tidyverse)
mtcars %>%
group_by(carb) %>%
summarise(n = n()) %>%
mutate(f = round(proportions(n) * 100, 1)) -> frq
mtcars %>%
group_by(gear) %>%
count(carb) -> df
df %>%
ggplot(aes(x = carb, y = n, fill = gear)) +
geom_bar(stat = "identity", position = "stack") +
geom_text(data = frq,
vjust = -1,
aes(x= carb, y = n, label = f),
inherit.aes = FALSE)
Created on 2022-10-31 by the reprex package (v2.0.1)

Changing text label color in ggplot bar chart for specific datapoints

I'm trying to change the color of the text labels associated with specific data points in a bar chart using ggplot2.
Here is the original code - using mtcars as an example:
mtcars_gear_percentage_by_make <- mtcars %>%
tibble::rownames_to_column(var = "car") %>%
tidyr::separate(car, c("make", "model"), sep = "\\s") %>%
dplyr::filter(make == "Merc" | make == "Toyota") %>%
dplyr::group_by(make, gear) %>%
dplyr::summarize(n_model = n()) %>%
dplyr::mutate(percentage_gear = n_model / sum(n_model, na.rm = TRUE))
ggplot(mtcars_gear_percentage_by_make,
aes(x = make, y = percentage_gear, fill = gear, label = round(percentage_gear, 2))) +
geom_col() +
geom_label(position = position_stack(vjust = 0.5))
And here is the plot it generates:
Is there a way to change the color of the text labels in the dark blue part to white, while leaving the color of the text labels in the lighter blue part unchanged?
Thank you!
A safer way to do this is to assign the colour aesthetic according to the fill group it will overlay:
ggplot(mtcars_gear_percentage_by_make,
aes(x = make, y = percentage_gear, fill = gear, label = round(percentage_gear, 2))) +
geom_col() +
geom_label(aes(colour = gear),
position = position_stack(vjust = 0.5)) +
scale_color_gradient(low = "white", high = "black", guide = guide_none())

How can I have different geom_text() labels in a faceted, stacked bar graph in R with ggplot?

I am trying to use facet_wrap with stacked bar graphs, and I'd like to have labels on the bars showing the value of each part of the bar.
Using the diamonds dataset as an example:
My geom_text code works fine when there is only one graph, albeit cramped for the shorter bars:
diamonds %>%
ggplot(aes(x = cut, fill = clarity)) +
geom_bar() +
geom_text(data = . %>%
group_by(cut, clarity) %>%
tally() %>%
ungroup() %>%
group_by(cut) %>%
ungroup(),
aes(y = n, label = n),
position = position_stack(0.5),
show.legend = FALSE)
Labeled bar plot without faceting
However, when I add the faceting, all the labels display in all the individual facets:
diamonds %>%
ggplot(aes(x = cut, fill = clarity)) +
geom_bar() +
facet_wrap(~ color) +
geom_text(data = . %>%
group_by(cut, clarity) %>%
tally() %>%
ungroup() %>%
group_by(cut) %>%
ungroup(),
aes(y = n, label = n),
position = position_stack(0.5),
show.legend = FALSE)
Faceted bar plot with replicated labeling
How can I make it so that the labels only show up on the relevant bars?
Thanks!
I think you need to include color in the group_by + tally so that it can be assigned to the correct facet:
diamonds %>%
ggplot(aes(x = cut, fill = clarity)) +
geom_bar() +
facet_wrap(~ color,scale="free_y") +
geom_text(data = . %>%
count(cut, clarity,color),
aes(y = n, label = n),size=1,
position = position_stack(0.5),
show.legend = FALSE)
Personally, I find the ..count.. special variable to be easier to work with.
diamonds %>%
ggplot(aes(x = cut, fill = clarity)) +
geom_bar() +
facet_wrap(~ color,scale="free_y") +
stat_count(geom = "text",
aes(y =..count.., label = ..count..),
position=position_stack(0.5), size = 2)

How to plot an area figure for a category variable

Here are two reproducible minimal examples for my request.
In the first one, the x variable is a factor variable, I find the function geom_area does not work, works like a geom_segment output.
In the second one, I transfer the x variable from factor into interger, the function geom_area works but I find the axis.text.y labels are not what I want.
Anyone know fix it?
suppressMessages(library(tidyverse))
mtcars %>%
rownames_to_column('index1') %>%
mutate(index1 = index1 %>% as.factor) %>%
mutate(index2 = index1 %>% as.integer) -> df
df %>%
ggplot() +
geom_area(aes(x = index1, y = mpg), color = 'black', fill = 'black') +
coord_flip()
df %>%
ggplot() +
geom_area(aes(x = index2, y = mpg), color = 'black', fill = 'black') +
coord_flip()
Check this solution:
library(tidyverse)
library(wrapr)
df %.>%
ggplot(data = .) +
geom_area(aes(x = index2, y = mpg), color = 'black', fill = 'black') +
coord_flip() +
scale_x_continuous(
breaks = .$index2,
labels = .$index1
)

R ggplot2: Adding another geom to coord_polar

I have a plot i wish to add another layer to
Th plot is below. I want to overlay another polar plot on it to see that the numbers "match up"
In the example below I have create the plot for one species of the iris dataset. I would like to overlay another plot of a different species
Thank you for your time
library(ggplot2)
library(dplyr)
mydf <- iris
plot.data <- tidyr::gather(mydf,key = attribute ,value = avg_score, Sepal.Length:Petal.Width)
plot.data <- plot.data %>%
filter(Species == 'setosa') %>%
group_by(attribute) %>%
summarise(attr_mean = mean(avg_score))
ggplot(plot.data, aes(x=attribute, y = attr_mean, col = attribute)) +
geom_bar(stat = "identity", fill = 'white') +
coord_polar(theta = "x") +
theme_bw()
This is quite the pedestrian way of doing things.
plot.setosa <- plot.data %>%
filter(Species == 'setosa') %>%
group_by(attribute) %>%
summarise(attr_mean = mean(avg_score))
plot.virginica <- plot.data %>%
filter(Species == 'virginica') %>%
group_by(attribute) %>%
summarise(attr_mean = mean(avg_score))
ggplot(plot.setosa, aes(x=attribute, y = attr_mean, col = attribute)) +
geom_bar(stat = "identity", fill = 'blue', alpha = 0.25) +
geom_bar(data = plot.virginica, stat = "identity", fill= "green", alpha = 0.25,
aes(x = attribute, y = attr_mean, col = attribute)) +
coord_polar(theta = "x") +
theme_bw()
And a slightly less pedestrian.
xy <- plot.data %>%
group_by(Species, attribute) %>%
summarise(attr_mean = mean(avg_score))
ggplot(xy, aes(x = attribute, y = attr_mean, color = attribute, fill = Species)) +
theme_bw() +
geom_bar(stat = "identity", alpha = 0.25) +
coord_polar(theta = "x")

Resources