How to make icons in geom_pictogram in r start at 0 - r

I am working on making a pictogram using r where the categories are along the x axis and the amount of the thing that belongs in each category is represented by the number of icons. I would like to leave the ticks on the y axis to make it easy to see how many of the thing there are, but the icons start a little above 0 and finish a little above the real value, giving the appearance that the value is higher than it really is.
# install.packages("waffle", repos = "https://cinc.rud.is")
library(waffle)
data <- data.frame(
x = c('John', 'James', 'Jeff', 'Joe', 'Jake'),
ht = c(72, 71, 73, 69, 66),
icon = rep('rocket', 5)
)
ggplot(data, aes(label= x,
values = ht,
color=icon)) +
geom_pictogram(n_rows=5, make_proportional=FALSE, size=5, flip=TRUE) +
facet_wrap(~x, nrow = 1, strip.position = "bottom") +
scale_x_discrete() +
scale_y_continuous(labels=function(x) x * 5, # multiplyer should be same as n_rows
expand = c(0,0),
limits = c(0,20)) +
scale_label_pictogram(
name = NULL,
values = c(
'rocket' = 'rocket'
)) +
theme(legend.position = "none")
This results in a good approximation of what I'm looking for, but without adjusting the alignment of the icons and the y-axis ticks/labels, it doesn't work.
I have been unable to find any way to move the y-axis ticks/labels higher or to shift the icons lower, either of which would work for this purpose. I have considered removing the y-axis ticks/labels and labeling the amount of the data just above each set of icons, but have been unable to get annotate or geom_text to work. I expect there's something simple I'm missing, but have no idea what it is at this point. I've also tried making this chart with echarts4r and waffle, though I've run into different issues with each that led me back to geom_pictogram.

One option would be to use geom_text with stat="waffle". Doing so allows to shift the icons aka labels via position_nudge:
library(ggplot2)
library(waffle)
ggplot(data, aes(
label = x,
values = ht,
color = icon
)) +
geom_text(
stat = "waffle", n_rows = 5, make_proportional = FALSE, size = 5, flip = TRUE,
family = "Font Awesome 5 Free",
position = position_nudge(y = -.9), vjust = 0
) +
facet_wrap(~x, nrow = 1, strip.position = "bottom") +
scale_x_discrete() +
scale_y_continuous(
labels = function(x) x * 5,
expand = c(0, 0),
limits = c(0, 20)
) +
scale_label_pictogram(
name = NULL,
values = c(
"rocket" = "rocket"
)
) +
theme(legend.position = "none")

If you want to use geom_pictogram (which always seems to start at 1), you could set the scale limits and add a custom label function to remove 1 from the values.
library(ggplot2)
library(waffle)
ggplot(data, aes(label= x,
values = ht,
color=icon)) +
geom_pictogram(n_rows=5,
size=5,
flip=TRUE) +
facet_wrap(~x, nrow = 1, strip.position = "bottom") +
scale_x_discrete() +
scale_label_pictogram(
name = NULL,
values = c(
'rocket' = 'rocket'
)) +
scale_y_continuous(
expand = c(0,0),
## here
limits = c(1, NA), labels = ~ .x-1, breaks = seq(1,20,5)) +
theme(legend.position = "none")

Related

Domain specific plotting using ggplot

I'm doing several domain specific plots using an excel template that looks like these .
My initial idea was to start with a blank plot and then add several segments and lines. But that appears not to be working well for me and taking much time to figure out. I was wondering if anyone has suggestion on how to accomplish this faster.
The plots types often changes too, not just this two types
I've seen this posts and they're different problems
Multiple Curves With Different Domains in a Single Plot ( with ggplot2)
Limit the domain of a custom function in R.
However, its somewhat similar to Reproduce a plot using ggplot. But my plots are more complex because like "B" in the image shared, they can have 4 axis.
Here’s an attempt at the top panel:
set.seed(13)
library(ggplot2)
library(geomtextpath)
xy_max <- 45
template_specs <- data.frame(
seg_x = seq(5, xy_max, by = 10),
seg_y = c(8, 21, 31, 39, 45),
seg_lab = seq(40, 0, by = -10)
)
template <- ggplot(template_specs) +
geom_textsegment(
aes(x = 0, xend = seg_x, y = seg_y, yend = 0, label = seg_lab),
offset = unit(-.75, "line"),
hjust = .45,
gap = FALSE
) +
geom_textsegment(
x = 0, xend = xy_max, y = xy_max, yend = 0,
label = "Intergranular Porosity (%)",
text_only = TRUE,
offset = unit(.75, "line"),
hjust = .25
) +
geom_segment(x = 0, y = 0, xend = xy_max/2, yend = xy_max/2) +
scale_x_continuous(
name = "CEPL (%)",
breaks = 0:9*5,
expand = c(0,0)
) +
scale_y_continuous(
name = "COPL (%)",
breaks = 0:9*5,
expand = c(0,0)
) +
theme_classic() +
theme(
legend.position = c(0.8, 0.8),
legend.title = element_blank()
)
template
example_data <- data.frame(
section = paste("Section", rep(LETTERS[1:8], 8)),
x = abs(rnorm(64, 0, 2)),
y = rnorm(64, 27.5, 7)
)
template +
geom_point(
data = example_data,
aes(x = x, y = y, color = section),
shape = 18,
size = 3
)

Adjusting position of colorbar tick labels in ggplot2

I'm trying to slightly reposition the labels of a discrete colorbar so that they don't overlap, without changing the values of the breaks themselves. In the below plot, the two center labels (bracketing the near-zero data) are too close together, so that it looks like '-11' instead of '-1' and '1'. I'd like to nudge them to either side, or change the justification of each half of the scale (left justify the negatives and right justify the positives), or anything to create more space between the labels while retaining the spacing of the actual colorbar. (Making the colorbar wider is not an option in my actual figure.)
Here is the code used to create this plot:
library(dplyr)
library(ggplot2)
library(scales)
df <- data.frame(
x = runif(1000),
y = runif(1000),
z1 = rnorm(100)*10
)
df %>% ggplot() +
geom_point(aes(x=x,y=y, color=z1)) +
scale_color_steps2(low = muted("darkblue"), mid = "white", high = muted("darkred"),
midpoint = 0, guide_colorbar(barwidth = 20),
breaks = c(-20, -10, -5, -1, 1, 5, 10, 20)) +
theme_minimal() +
theme(legend.position = 'bottom') +
labs(x='', y='', color='')
Always a bit hacky and you get a warning but one option would be to pass a vector to hjust argument of element_text to align the -1 to the right and the 1 to the left:
library(ggplot2)
set.seed(123)
df <- data.frame(
x = runif(1000),
y = runif(1000),
z1 = rnorm(100)*10
)
ggplot(df) +
geom_point(aes(x=x,y=y, color=z1)) +
scale_color_steps2(low = scales::muted("darkblue"), mid = "white", high = scales::muted("darkred"),
midpoint = 0, guide = guide_colorbar(barwidth = 20),# horizontal_legend,
breaks = c(-20, -10, -5, -1, 1, 5, 10, 20)) +
theme_minimal() +
theme(legend.position = 'bottom') +
labs(x='', y='', color='') +
theme(legend.text = element_text(hjust = c(rep(.5, 3), 1, 0, rep(.5, 3))))
#> Warning: Vectorized input to `element_text()` is not officially supported.
#> Results may be unexpected or may change in future versions of ggplot2.

How do I set y axis limits and breaks, and choose symbols in multiple variable in ggplot2?

df<-age_limbset
df$limbset<-as.factor(df$limbset)
limb_splot<-ggplot(df, aes(x=age,y=score))
limb_splot +
geom_point(aes(color = limbset, shape = limbset))+
geom_smooth(aes(color = limbset),
method = loess, se = FALSE, fullrange = TRUE)+
scale_color_manual(values = c("blue","hotpink"))+
scale_fill_manual(values = c("blue","hotpink"))+
ggpubr::stat_cor(aes(color = limbset),method="spearman", label.x = 3)+
labs(x="Age (years)",y="Total proprioception score (0-4)")+
scale_y_continuous(breaks=seq(0,4,0.5))+
scale_x_continuous(breaks=seq(2,16,2))+
theme_bw()
Sorry I do not know how to enter data here.
I have created this scatterplot showing relationship between age and proprioception of both forelimbs and hindlimbs. The plot is listening to my instruction for the x axis limits and breaks, but I can only get it to listen to either the limits OR the breaks for the y axis. What am I doing wrong?
How can I change the symbols for the data points? Ideally I would like them all to be dots.
I would also like to change the legend name and labels to start with a capital letter.
Here's an example of a reproducible example which also addresses your questions, e.g. with scale_shape_manual to get the shapes you want which you could choose here.
library(tidyverse)
tibble(years = rep(seq(2, 16, 1), 2),
score = abs(rnorm(30, 10, 10)),
set = rep(c("fore", "hind"), 15)
) |>
ggplot(aes(years, score, shape = set, colour = set)) +
geom_point() +
scale_shape_manual(values = c(1, 10)) +
scale_y_continuous(limits = c(0, 40), breaks = seq(0, 40, 5)) +
labs(x = "Years", y = "Score", shape = "Set", colour = "Set")
Created on 2022-05-04 by the reprex package (v2.0.1)

Issues with ggplotly within Shiny context

Using the code below, I could create the plot shown in the image. I am trying to fix some issues as follows:
1- How can I place the legend between title and plot. I would like to have the legend in a horizontal format rather than the current vertical form.
2- How can I bold, and center the plot title?
3- How can use different shapes in the geom_point function, depending on the "Disability" variable?
4- How can I rename the label so it reads "Age at Death" instead of the current name: "AgeatDeath"?
Thanks,
Nader
IDD_line <-
ggplot(IDD_plot) +
geom_line(aes(x = Year, y = AgeatDeath, color = Disability), size = 1) +
geom_point(aes(x = Year,
y = AgeatDeath,
color = Disability),
size = 1.5,
shape = 21) +
scale_x_continuous(breaks = seq(2008, 2017, 1)) +
labs(
x = "Year",
y = "Age at Death",
caption = (""),
face = "bold"
) +
theme_bw() +
scale_y_continuous(breaks = seq(35, 80, 5)) +
ggtitle(paste("Age of Death by Year (2008 to 2017)")) +
theme(
legend.title = element_blank(),
axis.text = (blue.bold.10.text),
legend.position = "top"
)
output$IDD_plot <- renderPlotly(ggplotly(IDD_line) %>%
config(displayModeBar = F))
This was a bit harder than I initially anticipated. Maybe somebody else will come up with some better solutions, but here's what I have.
How can I place the legend between title and plot. I would like to have the legend in a horizontal format rather than the current vertical form.
You can do this in layout after call to ggplotly. To put into horizontal form, use orientation = "h". If you specify y = 1.2 this will go above the plot (if you just set yanchor at "top" this will go on the plot itself near the top).
In addition, you'll want to add extra margin so the legend does not overlap with the title. Use margin to set left, right, bottom, and top margins (l, r, b, and t).
layout(legend = list(x = 0, y = 1.2, orientation = "h"),
margin = list(l = 50, r = 50, b = 100, t = 100)...
How can I bold, and center the plot title?
To bold the title, you can add HTML tags, such as <b>title</b> in ggtitle. To center the title, add that to layout as in #1, using xanchor:
layout(legend = list(x = 0, y = 1.2, orientation = "h"),
margin = list(l = 50, r = 50, b = 100, t = 100),
title = list(xanchor = "center", x = .5))
How can use different shapes in the geom_point function, depending on the "Disability" variable?
To get the shape to depend on "Disability", you will need shape = Disability in your aesthetic. The tricky part is that if you do this inside aes inside geom_point, you will get duplicate legends after converting to ggplotly. You can get around this with a separate aes outside of geom_point.
For more information see this github issue comment.
How can I rename the label so it reads "Age at Death" instead of the current name: "AgeatDeath"?
One method is to use text in your aes and clarify your labels this way. This will include line breaks with <br>, %d for integer values, and %s for string (for Disability):
text = sprintf("Year: %d<br>Age at Death: %d<br>Disability: %s",
Year, AgeatDeath, Disability)
Then, in your ggplotly call, include tooltip = "text".
So putting this all together, you have:
IDD_line <- ggplot(IDD_plot) +
aes(color = Disability,
shape = Disability,
group = Disability,
text = sprintf("Year: %d<br>Age at Death: %d<br>Disability: %s",
Year, AgeatDeath, Disability)) +
geom_line(aes(x = Year, y = AgeatDeath), size = 1) +
geom_point(aes(x = Year,
y = AgeatDeath),
size = 1.5) +
scale_x_continuous(breaks = seq(2008, 2017, 1)) +
labs(
x = "Year",
y = "Age at Death",
caption = (""),
face = "bold"
) +
theme_bw() +
scale_y_continuous(breaks = seq(35, 80, 5)) +
ggtitle(paste("<b>Age of Death by Year (2008 to 2017)</b>")) +
theme(
legend.title = element_blank(),
axis.text = (blue.bold.10.text) #,
#legend.position = "top"
)
And,
output$IDD_plot <- renderPlotly(
ggplotly(IDD_line, tooltip = "text") %>%
config(displayModeBar = F) %>%
layout(legend = list(x = 0, y = 1.2, orientation = "h"),
margin = list(l = 50, r = 50, b = 100, t = 100),
title = list(xanchor = "center", x = .5))
)

How to stop ggrepel labels moving between gganimate frames in R/ggplot2?

I would like to add labels to the end of lines in ggplot, avoid them overlapping, and avoid them moving around during animation.
So far I can put the labels in the right place and hold them static using geom_text, but the labels overlap, or I can prevent them overlapping using geom_text_repel but the labels do not appear where I want them to and then dance about once the plot is animated (this latter version is in the code below).
I thought a solution might involve effectively creating a static layer in ggplot (p1 below) then adding an animated layer (p2 below), but it seems not.
How do I hold some elements of a plot constant (i.e. static) in an animated ggplot? (In this case, the labels at the end of lines.)
Additionally, with geom_text the labels appear as I want them - at the end of each line, outside of the plot - but with geom_text_repel, the labels all move inside the plotting area. Why is this?
Here is some example data:
library(dplyr)
library(ggplot2)
library(gganimate)
library(ggrepel)
set.seed(99)
# data
static_data <- data.frame(
hline_label = c("fixed_label_1", "fixed_label_2", "fixed_label_3", "fixed_label_4",
"fixed_label_5", "fixed_label_6", "fixed_label_7", "fixed_label_8",
"fixed_label_9", "fixed_label_10"),
fixed_score = c(2.63, 2.45, 2.13, 2.29, 2.26, 2.34, 2.34, 2.11, 2.26, 2.37))
animated_data <- data.frame(condition = c("a", "b")) %>%
slice(rep(1:n(), each = 10)) %>%
group_by(condition) %>%
mutate(time_point = row_number()) %>%
ungroup() %>%
mutate(score = runif(20, 2, 3))
and this is the code I am using for my animated plot:
# colours for use in plot
condition_colours <- c("red", "blue")
# plot static background layer
p1 <- ggplot(static_data, aes(x = time_point)) +
scale_x_continuous(breaks = seq(0, 10, by = 2), expand = c(0, 0)) +
scale_y_continuous(breaks = seq(2, 3, by = 0.10), limits = c(2, 3), expand = c(0, 0)) +
# add horizontal line to show existing scores
geom_hline(aes(yintercept = fixed_score), alpha = 0.75) +
# add fixed labels to the end of lines (off plot)
geom_text_repel(aes(x = 11, y = fixed_score, label = hline_label),
hjust = 0, size = 4, direction = "y", box.padding = 1.0) +
coord_cartesian(clip = 'off') +
guides(col = F) +
labs(title = "[Title Here]", x = "Time", y = "Mean score") +
theme_minimal() +
theme(panel.grid.minor = element_blank(),
plot.margin = margin(5.5, 120, 5.5, 5.5))
# animated layer
p2 <- p1 +
geom_point(data = animated_data,
aes(x = time_point, y = score, colour = condition, group = condition)) +
geom_line(data = animated_data,
aes(x = time_point, y = score, colour = condition, group = condition),
show.legend = FALSE) +
scale_color_manual(values = condition_colours) +
geom_segment(data = animated_data,
aes(xend = time_point, yend = score, y = score, colour = condition),
linetype = 2) +
geom_text(data = animated_data,
aes(x = max(time_point) + 1, y = score, label = condition, colour = condition),
hjust = 0, size = 4) +
transition_reveal(time_point) +
ease_aes('linear')
# render animation
animate(p2, nframes = 50, end_pause = 5, height = 1000, width = 1250, res = 120)
Suggestions for consideration:
The specific repelling direction / amount / etc. in geom_text_repel is determined by a random seed. You can set seed to a constant value in order to get the same repelled positions in each frame of animation.
I don't think it's possible for repelled text to go beyond the plot area, even if you turn off clipping & specify some repel range outside plot limits. The whole point of that package is to keep text labels away from one another while remaining within the plot area. However, you can extend the plot area & use geom_segment instead of geom_hline to plot the horizontal lines, such that these lines stop before they reach the repelled text labels.
Since there are more geom layers using animated_data as their data source, it would be cleaner to put animated_data & associated common aesthetic mappings in the top level ggplot() call, rather than static_data.
Here's a possible implementation. Explanation in annotations:
p3 <- ggplot(animated_data,
aes(x = time_point, y = score, colour = condition, group = condition)) +
# static layers (assuming 11 is the desired ending point)
geom_segment(data = static_data,
aes(x = 0, xend = 11, y = fixed_score, yend = fixed_score),
inherit.aes = FALSE, colour = "grey25") +
geom_text_repel(data = static_data,
aes(x = 11, y = fixed_score, label = hline_label),
hjust = 0, size = 4, direction = "y", box.padding = 1.0, inherit.aes = FALSE,
seed = 123, # set a constant random seed
xlim = c(11, NA)) + # specify repel range to be from 11 onwards
# animated layers (only specify additional aesthetic mappings not mentioned above)
geom_point() +
geom_line() +
geom_segment(aes(xend = time_point, yend = score), linetype = 2) +
geom_text(aes(x = max(time_point) + 1, label = condition),
hjust = 0, size = 4) +
# static aesthetic settings (limits / expand arguments are specified in coordinates
# rather than scales, margin is no longer specified in theme since it's no longer
# necessary)
scale_x_continuous(breaks = seq(0, 10, by = 2)) +
scale_y_continuous(breaks = seq(2, 3, by = 0.10)) +
scale_color_manual(values = condition_colours) +
coord_cartesian(xlim = c(0, 13), ylim = c(2, 3), expand = FALSE) +
guides(col = F) +
labs(title = "[Title Here]", x = "Time", y = "Mean score") +
theme_minimal() +
theme(panel.grid.minor = element_blank()) +
# animation settings (unchanged)
transition_reveal(time_point) +
ease_aes('linear')
animate(p3, nframes = 50, end_pause = 5, height = 1000, width = 1250, res = 120)

Resources