Reputation: 97
I have a a vector v3 with levels: setosa versicolor virginica
When I plot the vector using the basic plot function;
plot(v3, type = "s", xlim = NULL, ylim = c(0,50),
main = "Plot 2", ylab = 'Frequency', col = "blue")
I get the following plot
But the output I would like to create looks like this:
I know certain (more elegant) solutions exist but I would like to create this without installing & loading additional packages. I tried the following with axis:
axis(1, at = c(0,50), labels = FALSE, tick = TRUE)
axis(2, at = levels(v3), labels = FALSE, tick = TRUE)
But R would not accept it.
Thanks for any input!
Upvotes: 0
Views: 108
Reputation: 21400
It seems what you are looking for is a barplot rather than a scatter plot. Let's say you have data like this:
DATA:
set.seed(321)
v3 <- sample(c("setosa", "versicolor", "virginica"), 100, replace = T)
v3
[1] "versicolor" "versicolor" "setosa" "setosa" "setosa" "versicolor" "versicolor" "setosa"
[9] "virginica" "virginica" "setosa" "virginica" "versicolor" "virginica" "versicolor" "virginica"
[17] "setosa" "versicolor" "virginica" "virginica" "versicolor" "versicolor" "virginica" "versicolor"
[25] "virginica" "versicolor" "setosa" "versicolor" "setosa" "virginica" "setosa" "setosa"
[33] "virginica" "versicolor" "setosa" "virginica" "versicolor" "setosa" "versicolor" "setosa"
[41] "virginica" "versicolor" "setosa" "virginica" "setosa" "versicolor" "versicolor" "setosa"
[49] "setosa" "virginica" "virginica" "virginica" "setosa" "virginica" "versicolor" "versicolor"
[57] "setosa" "setosa" "virginica" "setosa" "setosa" "versicolor" "virginica" "virginica"
[65] "virginica" "setosa" "virginica" "versicolor" "versicolor" "versicolor" "virginica" "versicolor"
[73] "virginica" "setosa" "setosa" "versicolor" "virginica" "versicolor" "versicolor" "versicolor"
[81] "versicolor" "virginica" "setosa" "virginica" "setosa" "versicolor" "virginica" "setosa"
[89] "versicolor" "versicolor" "virginica" "setosa" "virginica" "virginica" "virginica" "versicolor"
[97] "setosa" "virginica" "virginica" "setosa"
What you cannot do is plot factor levels; you can only count the number of times the levels occur in your data: these frequencies you can plot. You can do this by tabulating the vector v3
using the table
function. To flip the bars into horizontal position you can use the argument horiz = TRUE
(doing that will also necessitate that you put the label Frequency
onto the x-axis rather than the y-axis):
barplot(table(v3), horiz = T, main = "Plot 2",
xlab = 'Frequency',
ylab = 'Species',
col = 'blue')
RESULT:
The resulting barplot would look like this:
Upvotes: 3