thomasp85 / ggforce

Accelerating ggplot2
https://ggforce.data-imaginist.com
Other
916 stars 105 forks source link

Fix x label in 'gather_set_data' function #305

Closed ycl6 closed 7 months ago

ycl6 commented 1 year ago

This PR fix a bug in the gather_set_data function where the x values in the returned dataframe is the indices of the column names instead of the column names themselves. The tidyselect::eval_select() returns a vector where the elements are the indices and the names of the vector are the actual column names. As a result, the x-axis in the ggplot is not showing the labels correctly.

    library(ggforce) # ggforce_0.4.1
    #> Loading required package: ggplot2

    data <- reshape2::melt(Titanic)
    data <- gather_set_data(data, 1:4)
    head(data)
    #>   Class    Sex   Age Survived value id x    y
    #> 1   1st   Male Child       No     0  1 1  1st
    #> 2   2nd   Male Child       No     0  2 1  2nd
    #> 3   3rd   Male Child       No    35  3 1  3rd
    #> 4  Crew   Male Child       No     0  4 1 Crew
    #> 5   1st Female Child       No     0  5 1  1st
    #> 6   2nd Female Child       No     0  6 1  2nd

    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')

    # Fixed function in this PR
    gather_set_data <- function(data, x, id_name = 'id') {
      columns <- tidyselect::eval_select(enquo(x), data)
      data[[id_name]] <- seq_len(nrow(data))
      vctrs::vec_rbind(!!!lapply(names(columns), function(n) {
        data$x <- n
        data$y <- data[[n]]
        data
      }))
    }

    data <- reshape2::melt(Titanic)
    data <- gather_set_data(data, 1:4)
    head(data)
    #>   Class    Sex   Age Survived value id     x    y
    #> 1   1st   Male Child       No     0  1 Class  1st
    #> 2   2nd   Male Child       No     0  2 Class  2nd
    #> 3   3rd   Male Child       No    35  3 Class  3rd
    #> 4  Crew   Male Child       No     0  4 Class Crew
    #> 5   1st Female Child       No     0  5 Class  1st
    #> 6   2nd Female Child       No     0  6 Class  2nd

    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')

Created on 2023-07-20 with reprex v2.0.2

thomasp85 commented 7 months ago

Thank you!