【问题标题】:Factor variable on x-axis for double y-axis双 y 轴的 x 轴上的因子变量
【发布时间】:2022-01-13 00:54:38
【问题描述】:

现在它在 x 轴上绘制数值变量“1,2,3,4”等,而我希望它绘制游戏图。正如您在第 85 行中看到的,axis(1,Champ$game) 我想要游戏名称在 x 轴上,但它只是为游戏编号而不是放置游戏名称。我该如何解决?

par(mar=c(5, 4, 4, 6) + 0.1)
plot(Champ$daily_max_vel, pch = 16, axes = FALSE, ylim = 
c(3.0,3.9),type = "b", col = "black", ylab = "", xlab = "",
                                main = "Athlete")
##Creates y-axis for graph 1
axis(2, ylim = c(0,1), col = "black", las = 1)
mtext("Velocity (m/s)", side = 2, line = 2.5)
box()

## Allows for second plot on same graph
par(new = TRUE)

#Plotting second graph
plot(Champ$daily_peak_power, pch = 1, xlab = "", ylab = "", 
ylim = c(1000,1600), axes = FALSE, type = "b", 
                                  col = "orange")
 #Creating Second Axis
 mtext("Power (W)", side = 4, col = "orange", line = 4)
 axis(4,ylim = c(1200,1600), col = "orange", col.axis = 
 "orange", las = 1)
 axis(1,Champ$game)

【问题讨论】:

  • 您能否尝试给我们您的数据样本,例如使用dput() 或其他方法?请使用实际代码,而不是截图

标签: r plot


【解决方案1】:

使用 labels 函数应该可以满足您的需求 - 这是我认为您的问题的一个示例。如果这不起作用,请编辑您的帖子以提供您的数据结构。

# create sample data 
df <-  data.frame(game = sample(c(1, 2, 3), 150, replace = TRUE),val = rgamma(150, 50))
plot(df)

# label factors
df$game <-  factor(df$game, levels = 1:3, labels = c("Game A", "Game B", "Game C"))

# plot
plot(df, axes = F, type = "b")
axis(1, df$game, labels = df$game) # shows game A, game b, game c instead of 1, 2, 3

【讨论】:

  • 嗨@jpsmith,我更新了这个问题,所以你可以看到我正在处理什么。我认为我不需要标签功能,因为游戏名称已经在表中作为一个因素。这是正确的还是我理解不正确?
  • 嗨 Ben - R 中的因子存储为整数值(在幕后),并带有一组相应的字符值,通常在显示因子时(即 print(df) 时)使用。这就是为什么您在 x 轴上获得整数的原因。通过使用标签函数,您是在告诉它使用相应的字符值。
猜你喜欢
  • 2019-10-21
  • 1970-01-01
  • 1970-01-01
  • 2021-07-24
  • 1970-01-01
  • 2014-05-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多