naco - 11 months ago 91

R Question

I want to organize my data by one category on the X-axis, but color it by another category as in this example:

Graph #1, without coloring:

`require(ggplot2)`

nocolor <- ggplot(mtcars, aes(x=as.factor(cyl), y=disp)) +

geom_dotplot(binaxis="y", stackdir = "center")

print(nocolor)

Graph #2, with coloring:

`nododge <- ggplot(mtcars, aes(x=as.factor(cyl), y=disp, fill=as.factor(gear))) +`

geom_dotplot(binaxis="y", stackdir = "center")

print(nododge)

One problem that occurs after introducing coloring is that the dots belonging to different groups wont dodge one another anymore. This causes problems with my real data, as I get dots that happen to have the same value and completely obscure one another.

Then I tried this, but it garbled my data:

Graph #3

`garbled <- ggplot(mtcars, aes(x=as.factor(cyl), y=disp)) +`

geom_dotplot(binaxis="y", stackdir = "center", fill=as.factor(mtcars$gear))

print(garbled)

The dots dodge one another, but the the coloring is just random and is not true to the actual data.

I expected the answer to this question to solve my problem, but the coloring remained random:

Graph #4

`graphdata <- mtcars`

graphdata$colorname <- as.factor(graphdata$gear)

levels(graphdata$colorname) <- c("red", "blue", "black")

jalapic <- ggplot(graphdata, aes(x=as.factor(cyl), y=disp)) +

geom_dotplot(binaxis="y", stackdir = "center", fill=as.character(graphdata$colorname))

print(jalapic)

Does anyone have an idea how to get the dots in Graph #2 to dodge one another, or how to fix the coloring in graphs 3 or 4? I would really appreciate any help, thanks.

Answer Source

Using `binpositions="all"`

and `stackgroups=TRUE`

:

```
ggplot(mtcars, aes(x=as.factor(cyl), y=disp, fill=as.factor(gear))) +
geom_dotplot(binaxis="y", stackdir = "center", binpositions="all", stackgroups=TRUE)
```

gives:

A possible alternative is using `stackdir = "up"`

:

```
ggplot(mtcars, aes(x=as.factor(cyl), y=disp, fill=as.factor(gear))) +
geom_dotplot(binaxis="y", stackdir = "up", binpositions="all", stackgroups=TRUE)
```

which gives: