plotbiomes icon indicating copy to clipboard operation
plotbiomes copied to clipboard

italicize text

Open valentinitnelav opened this issue 1 year ago • 1 comments

Got this email:

I am using your plot_bipartite() function to make some plots and I was wondering if you know of a way to partially italicize text on one side of the plot so that species epithet abbreviations can be plain text while the genus names are italicized?

valentinitnelav avatar Dec 14 '24 09:12 valentinitnelav

It is a bit unclear whether the question refers to the legend, axis labels, or another text element in a ggplot2 plot. Below is an example demonstrating how to add an additional legend for taxa. I created some sample data containing text where either the first or second word can be italicized, as shown in two examples: one with the first word italicized and another with the second word italicized.

library(plotbiomes)
#>      Happy biome plotting!
library(ggplot2)
library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union

# Fake data
fake_data <- data.frame(
  temp = c(10, 15, 20),
  pp_cm = c(100, 200, 150),
  taxa = c("Some taxa_1", "Some taxa_2", "Other taxa_3")
)

# Dynamically create formatted labels with the first word italicized
fake_data <- fake_data %>%
  mutate(
    taxa_label = gsub("(\\w+) (\\w+)", "italic('\\1')~'\\2'", taxa)
  )

# Create a plot with automatic legend
whittaker_base_plot() +
  geom_point(data = fake_data,
             aes(x = temp, 
                 y = pp_cm,
                 color = taxa_label)) +  # Map formatted labels to color
  scale_color_manual(
    values = setNames(c("blue", "red", "green"), fake_data$taxa_label),
    labels = parse(text = fake_data$taxa_label),  # Parse dynamic labels
    guide = guide_legend(order = 1) # Ensure this legend is on top of the "Whittaker biomes" default legend
  ) +
  labs(color = "Taxa") +  # Adjust legend title
  theme_minimal()




# Dynamically create formatted labels with the second word italicized
fake_data <- fake_data %>%
  mutate(
    taxa_label = gsub("(\\w+) (\\w+)", "'\\1'~italic('\\2')", taxa)
  )

# Create a plot with automatic legend
whittaker_base_plot() +
  geom_point(data = fake_data,
             aes(x = temp, 
                 y = pp_cm,
                 color = taxa_label)) +  # Map formatted labels to color
  scale_color_manual(
    values = setNames(c("blue", "red", "green"), fake_data$taxa_label),
    labels = parse(text = fake_data$taxa_label),  # Parse dynamic labels
    guide = guide_legend(order = 1) # Ensure this legend is on top of the "Whittaker biomes" default legend
  ) +
  labs(color = "Taxa") +  # Adjust legend title
  theme_minimal()

Created on 2024-12-14 with reprex v2.1.0

valentinitnelav avatar Dec 14 '24 10:12 valentinitnelav