简体   繁体   English

如何使用 ggplot2 绘制数字序列

[英]How do I plot a sequence of number using ggplot2

Suppose I have a sequence of numbers:假设我有一个数字序列:

> dput(firstGrade_count)
c(4L, 346L, 319L, 105L, 74L, 5L, 124L, 2L, 10L, 35L, 6L, 206L, 
7L, 8L, 6L, 9L, 26L, 1L, 35L, 18L, 4L, 4L, 2L, 63L, 6L, 23L, 
6L, 82L, 10L, 17L, 45L, 74L, 10L, 8L, 14L, 23L, 26L, 53L, 55L, 
16L, 2L, 141L, 113L, 98L, 179L, 13L, 34L, 16L, 8L, 144L, 2L, 
141L, 26L, 9L, 125L, 201L, 32L, 452L, 179L, 30L, 4L, 141L, 5L, 
40L, 7L, 255L, 120L, 223L, 28L, 252L, 21L, 8L, 362L, 4L, 5L, 
2L, 285L, 18L, 76L, 5L, 73L, 11L, 367L, 7L, 50L, 6L, 37L, 15L, 
48L, 5L, 12L, 7L, 96L)

I want to plot it using ggplot2 so the result would be something similar to:我想使用ggplot2绘制它,因此结果将类似于:

barplot(firstGrade_count)

How would I define the aesthetics in ggplot2?我将如何定义 ggplot2 中的美学?

Here is the plot produced by base plot that I mentioned above:这是我上面提到的基本图生成的图:

在此处输入图片说明

firstGrade_count  <- c(4,346,319,105,74,5,124,2,10,35,6,206,7,8,6,9,26,1,35,18,4,4,2,63,6,23,6,
82,10,17,45,74,10,8,14,23,26,53,55,16,2,141,113,98,179,13,34,16,8,144,2,141,26,9,
125,201,32,452,179,30,4,141,5,40,7,255,120,223,28,252,21,8,362,4,5,2,285,18,76,5,73,
11,367,7,50,6,37,15,48,5,12,7,96)

You can optionally make this into a data frame to make it easier to work with and to hold any additional features, though it's not required.您可以选择将其放入数据框,以便更轻松地使用和保存任何其他功能,尽管这不是必需的。

library(ggplot2)

# Optional transformation to data.frame:
firstGrade_count <- as.data.frame(firstGrade_count)

# Index for x-coordinates
firstGrade_count$index <- seq(1:nrow(firstGrade_count))

# Plotting
c <- ggplot(firstGrade_count, aes(index,firstGrade_count))
c + geom_bar(stat = "identity") 

在此处输入图片说明

Or,或者,

firstGrade_count <- as.data.frame(firstGrade_count)
c <- ggplot(firstGrade_count, aes(factor(firstGrade_count)))
c + geom_bar()

The way I set it up shows you the count of each unique value.我的设置方式向您展示了每个唯一值的计数。 There are many variations and additional formats you could add:您可以添加许多变体和其他格式:

在此处输入图片说明

If you don't want the count you can add the stat = option and change it from the default to something else.如果您不想要计数,您可以添加stat =选项并将其从默认值更改为其他值。

Without creating any dataframe:不创建任何数据框:

ggplot() + 
geom_bar(aes(1:length(firstGrade_count),firstGrade_count), stat='identity') + 
xlab('')

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM