r - 按行索引(数据的原始顺序)而不是按字母顺序设置 ggplot 中 x 或 y 的顺序

标签 r ggplot2 plot tidyverse

我想根据数据的原始顺序而不是按字母或数字顺序绘制数据(从上到下的顺序应类似于变量 d 、变量 a 、变量 c 和变量 b ) 。我的 df 如下​​所示:

df <- tribble(
  ~variables, ~names, ~values,
  'vard', "D", 2.5,
  'vard', "D", 3.5,
  'vard', "D", 4.9,
  'vara', "A", 2.5,
  'vara', "A", 3.5,
  'vara', "A", 4.9,
  'varc', "C", 8.5,
  'varc', "C", 7.3,
  'varc', "C", 6.1,
  'varb', "B", 3.1,
  'varb', "B", 5.2,
  'varb', "B", 7.8
)

df %>% ggplot(aes(x = variables, y = values)) + coord_flip()

enter image description here

最佳答案

试试这个:

new_levels <- df$variables %>% unique %>% rev
df <- df %>% mutate(variables = factor(variables, levels = new_levels))
df %>% ggplot( aes(x=variables, y=values)) + coord_flip()

enter image description here

关于r - 按行索引(数据的原始顺序)而不是按字母顺序设置 ggplot 中 x 或 y 的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75774341/

相关文章:

regex - 从字符串向量中提取数字

r - 使用 ggplot2 堆积点图

r - 在 R 中绘制数据框中的多条线

python - 绘制二维矩阵中特征的存在情况

plot - Gnuplot 标签中的符号

r - 快速合并(..., all = TRUE) 与 R 中的 data.table

R在data.table中查找间隔

r - 如何使用R从基于外部列表的data.frame中删除行?

r - 在ggplot2中一起使用构面标签和 strip 标签

r - 自定义ggplot中y轴标签的顺序