scale_x_discrete标签在R的ggplot中消失了

时间:2017-02-26 21:13:20

标签: r ggplot2 data-visualization scatter-plot

我是R中的新手,由于某种原因,我的情节中X的值消失了,我在很多页面中发现如何更改它但不设置为默认值,我的意思是固定酸度的值。我不知道它是如何被删除的。

代码:

ggplot(redwine, aes(x = fixed.acidity, y = density, col = quality)) + 
  geom_point(alpha = 0.3) + stat_smooth(method = "lm", col = "red", se = FALSE) +
  scale_x_discrete("Fixed Acidity") + scale_y_continuous("Density") +
  scale_color_continuous("Quality") 

关注我的数据:

    redwine <- structure(list(fixed.acidity = c(7.4, 7.8, 7.8, 11.2, 7.4, 7.4
), volatile.acidity = c(0.7, 0.88, 0.76, 0.28, 0.7, 0.66), citric.acid = c(0, 
0, 0.04, 0.56, 0, 0), residual.sugar = c(1.9, 2.6, 2.3, 1.9, 
1.9, 1.8), chlorides = c(0.076, 0.098, 0.092, 0.075, 0.076, 0.075
), free.sulfur.dioxide = c(11, 25, 15, 17, 11, 13), total.sulfur.dioxide = c(34, 
67, 54, 60, 34, 40), density = c(0.9978, 0.9968, 0.997, 0.998, 
0.9978, 0.9978), pH = c(3.51, 3.2, 3.26, 3.16, 3.51, 3.51), sulphates = c(0.56, 
0.68, 0.65, 0.58, 0.56, 0.56), alcohol = c(9.4, 9.8, 9.8, 9.8, 
9.4, 9.4), quality = c(5L, 5L, 5L, 6L, 5L, 5L)), .Names = c("fixed.acidity", 
"volatile.acidity", "citric.acid", "residual.sugar", "chlorides", 
"free.sulfur.dioxide", "total.sulfur.dioxide", "density", "pH", 
"sulphates", "alcohol", "quality"), row.names = c(NA, 6L), class = "data.frame")

TKS

enter image description here

1 个答案:

答案 0 :(得分:0)

这是一个模拟示例,展示了如何正确设置标签和轴文本

如果您只想设置轴标签,那么最简单的方法是使用labs功能

library(ggplot2)

set.seed(123)
redwine <- data.frame(fixed.acidity = rnorm(n = 100),
                                            density = rnorm(n = 100),
                                            quality = rnorm(n = 100))

## replace the 'scale_x_discrete' with 'labs'
ggplot(redwine, aes(x = fixed.acidity, y = density, col = quality)) + 
    geom_point(alpha = 0.3) + stat_smooth(method = "lm", col = "red", se = FALSE) +
    #scale_x_discrete("Fixed Acidity") + 
    #scale_y_continuous("Density") +
    labs(x = "Fixed Acidity", y = "Density") 
    #scale_color_continuous("Quality") 

enter image description here

如果要格式化轴标签,可以在theme()功能

中执行此操作
ggplot(redwine, aes(x = fixed.acidity, y = density, col = quality)) + 
    geom_point(alpha = 0.3) + stat_smooth(method = "lm", col = "red", se = FALSE) +
    labs(x = "Fixed Acidity", y = "Density") +
    theme(axis.text.x = element_text(angle = 90, size = 16))

enter image description here