散点图显示直线而不是散点,如何解决?

时间:2019-04-08 22:35:34

标签: r ggplot2

我正在分析我的数据集-费城地区的种族,职业和收入数据。

我本来希望使用ggplot进行各种数据可视化,但是我什至很难得到一个正常显示的麻烦。每个地块都显得异常拥挤。我做错了。也许使用ggplot,也许使用分解因子,但是我不确定。

这是我最新的一个散点图。

ggplot(cps_data2, aes(x = INCWAGE_factor,
                      y = RACE_factor)) + 
xlab('Individual Income') + 
ylab('Race') +
geom_point()

这给了我这个:

enter image description here

这是我的数据集信息。 (请参阅有关如何对变量进行因子分解的示例。)

cps_data2<-cps_data2 %>%
  mutate(INCWAGE_factor = as_factor(INCWAGE))

$ RACE_factor   : Factor w/ 9 levels "White","Black/African American/Negro",..: 1 1 2 2 1 8 2 1 1 2 ...
  ..- attr(*, "label")= chr "Race [general version]"

$ OCC_factor    : Factor w/ 429 levels "0","10","20",..: 42 302 1 22 254 291 1 112 418 1 ...
  ..- attr(*, "label")= chr "Occupation"

$ INCWAGE_factor: Factor w/ 654 levels "0","20","50",..: 521 283 1 529 328 311 1 1 283 1 ...
  ..- attr(*, "label")= chr "Wage and salary income"

$ SEX_factor    : Factor w/ 2 levels "Male","Female": 2 1 2 1 2 1 1 2 1 2 ...
  ..- attr(*, "label")= chr "Sex"

$ CITY_factor   : Factor w/ 1157 levels "Not in identifiable city (or size group)",..: 814 814 814 814 814 814 814 814 814 814 ...
  ..- attr(*, "label")= chr "City"

$ AGE_factor    : Factor w/ 46 levels "Less than 1 year old",..: 14 12 37 18 35 14 39 41 37 36 ...
  ..- attr(*, "label")= chr "Age"

3 个答案:

答案 0 :(得分:0)

您的X和Y变量都是分类因素。 y轴是分类变量(例如race)的期望值。

一项改进是将x轴变量更改为数字:cps_data2$INCWAGE_factor <- as.numeric(as.character(cps_data2$INCWAGE_factor))

如果您想更清楚地看到自己的观点,则应查看geom_jitter(),它会在数据中添加任意数量的噪声以进行图形显示。见下文:

library(tidyverse)

#toy data
z <- data.frame(x = rep(c('one','two','one','two'),50), y = rnorm(1,50))

#without jitter
ggplot(z, aes(x,y)) + geom_point()

#with jitter
ggplot(z, aes(x,y)) + geom_point() + geom_jitter()

无抖动 enter image description here 有抖动 enter image description here

当然,当涉及到分类变量时,可能还有其他方法可以探索您的数据。正如其他人指出的那样,箱形图和晶须图是常见的geom_boxplot()

答案 1 :(得分:0)

这里与您的情节相似,假设mpg是一个数字变量:

ggplot(mtcars, aes(mpg, as.factor(cyl))) + 
  geom_point()

enter image description here

使用ggridges软件包,这可能对您有用。

ggplot(mtcars, aes(mpg, as.factor(cyl))) + 
  ggridges::geom_density_ridges()

enter image description here

这是一种使用geom_boxplot的方法,该方法通常是垂直定向的,需要在此处翻转。

ggplot(mtcars, aes(as.factor(cyl), mpg)) + geom_boxplot() + coord_flip()

enter image description here

答案 2 :(得分:0)

有时候,简单的视觉效果只是在透明的点上增加密度的概念:带有附加参数的代码。

ggplot(cps_data2, aes(x = INCWAGE_factor,
                      y = RACE_factor)) + 
xlab('Individual Income') + 
ylab('Race') +
geom_point(shape = 1, alpha = 0.2)
相关问题