绘制非数字数据

时间:2016-01-25 02:15:02

标签: r plot

我们如何在R中绘制非数字数据?我想针对aa绘制(使用任何图形类型 - 例如,boxplot或直方图...等)bb。我希望在我的x轴上有bb,在我的y轴上有aa

class(aa)
# [1] "character"
class(bb)
# [1] "character"

1 个答案:

答案 0 :(得分:1)

您可以使用dplyrggplot

假设您提供的输入位于df(请参阅本文底部的输入数据)

library(dplyr)
library(ggplot)

## Assuming the data is in the file 'Types.csv'
df <- read.csv('Types.csv')

df_summary <-
    df                          %>% # Pipe df into group_by
    group_by(type)              %>% # grouping by 'type' column
    summarise(name_count = n())     # calculate the name count for each group
## 'df_summary' now contains the summary data for each 'type'
df_summary

##     type name_count
##    (chr)      (int)
##1     dos          6
##2  normal          1
##3   probe          4
##4     r2l          8
##5     u2r          4
##6 unknown          1

### Two ways to plot using ggplot

## (1) Plot pre summarized data: 'df_summary'.
ggplot(df_summary, aes(type, name_count)) +  # 
    geom_bar(stat = 'identity')              # stat='identity' is used for summarized data.

## (2) Bar plot on original data frame (not summarised)
ggplot(df, aes(type))      +
    geom_bar()             + # 'stat' isn't needed here.
    labs(y = 'name_count')

以下是df_summary

的情节

enter image description here

您还可以执行以下操作来添加标签和绘图标题(未显示此

的绘图结果)
ggplot(df, aes(type)) +
    geom_bar() +
    labs(x = 'Type', y = 'Count') +
    ggtitle('Type Counts')

要在条形图上方添加文本标签(在本例中为每个类别的频率),可以按以下方式添加geom_text(图表结果未显示)。

ggplot(df_summary, aes(type, name_count)) +
    geom_bar(stat = 'identity') +
    geom_text(aes(label = name_count), vjust = -1) +
    ggtitle('Type Counts')

## OR

ggplot(df, aes(type)) +
    geom_bar() +
    labs(x = 'Type', y = 'Count') +
    geom_text(stat = 'count', aes(label = ..count..), vjust = -1) +
    ggtitle('Type Counts')

输入数据

df <- read.table(header=TRUE, stringsAsFactors=FALSE, text='
         name    type
           back     dos
buffer_overflow     u2r
      ftp_write     r2l
   guess_passwd     r2l
           imap     r2l
        ipsweep   probe
           land     dos
     loadmodule     u2r
       multihop     r2l
        neptune     dos
           nmap   probe
           perl     u2r
            phf     r2l
            pod     dos
      portsweep   probe
        rootkit     u2r
          satan   probe
          smurf     dos
            spy     r2l
       teardrop     dos
    warezclient     r2l
    warezmaster     r2l
         normal  normal
        unknown unknown')