Search code examples
rchartsggforce

Loosing names for x values on x-axis in parallel sets chart with ggforce in R


According to this example: https://ggforce.data-imaginist.com/reference/geom_parallel_sets.html

This code

library(ggforce)
library(reshape2)
library(ggplot2)

data <- reshape2::melt(Titanic)
data <- gather_set_data(data, 1:4)

ggplot(data, aes(x, id = id, split = y, value = value)) +
  geom_parallel_sets(aes(fill = Sex), alpha = 0.3, axis.width = 0.1) +
  geom_parallel_sets_axes(axis.width = 0.1) +
  geom_parallel_sets_labels(colour = 'white')

should return enter image description here

(note the names on the x-axis)

But when I run the same code I get: enter image description here

I.e., the names on the x-axis is not present. Anyone has a fix for this?


Solution

  • Looks like a bug to me. The issue is that the column names get dropped inside gather_set_data. Not sure whether this is due to a change in ggforce or one of the dependencies.

    A possible workaround would be to manually re-label the x column like so:

    Note: The issue was already reported on GH and there is already a (partial) fix in the dev version. IMHO only partial as it does not preserve the order of the columns.

    library(ggforce)
    #> Loading required package: ggplot2
    library(reshape2)
    library(ggplot2)
    
    data <- reshape2::melt(Titanic)
    
    data <- gather_set_data(data, 1:4) |> 
      transform(x = factor(x, labels = names(data)[1:4]))
    
    ggplot(data, aes(x, id = id, split = y, value = value)) +
      geom_parallel_sets(aes(fill = Sex), alpha = 0.3, axis.width = 0.1) +
      geom_parallel_sets_axes(axis.width = 0.1) +
      geom_parallel_sets_labels(colour = "white")