如何在ggplot中将索引号用作x?

Cpt*_*nic 17 r ggplot2

这似乎应该很容易,但我无法弄清楚.我有一个数据框,其中行名称自动创建为索引编号,如下面的示例所示.

> df
    employee salary  startdate
1   John Doe  21000 2010-11-01
2 Peter Gynn  23400 2008-03-25
3 Jolie Hope  26800 2007-03-14
Run Code Online (Sandbox Code Playgroud)

我想使用x轴上的行名称来绘制它,但由于它没有名称,我无法弄清楚这一点.有人能指出我正确的方向吗?

Pau*_*oso 18

对我来说并不是很清楚(映射到y的是什么?)但是

df <- structure(list(employee = c("John Doe", "Peter Gynn", "Jolie Hope"),
                     salary = c(21000L, 23400L, 26800L),
                     startdate = c("2010-11-01", "2008-03-25", "2007-03-14")),
                .Names = c("employee", "salary", "startdate"),
                row.names = c(NA, -3L), class = "data.frame")
# if row.names are strings
df$idu <- row.names(df)
# if row numbers are integers (most likely!)
df$idu <- as.numeric(row.names(df))

df

library(ggplot2)

ggplot(aes(x=idu, y = salary), data = df) +
  geom_bar(stat = 'identity')
Run Code Online (Sandbox Code Playgroud)

或使用@MrFlick中没有idu列的建议

ggplot(aes(x = as.numeric(row.names(df)), y = salary), data = df) +
  geom_bar(stat = 'identity') +
  labs(x='ID')
Run Code Online (Sandbox Code Playgroud)

geom_bar

  • `x = 1:nrow(df)`? (8认同)
  • 如果有超过9行,则需要将行名转换为数字:`as.numeric(row.names(df))`.否则,排序无法正常工作. (3认同)