为因子变量制作频率直方图

时间:2014-02-07 23:05:02

标签: r histogram categorical-data

我对R很新,所以我为这样一个基本问题道歉。我花了一个小时来搜索这个问题,但找不到解决方案。

假设我的数据集中有一些关于常见宠物类型的分类数据。我将它作为R中的字符向量输入,其中包含不同类型动物的名称。我这样创建了它:

animals <- c("cat", "dog",  "dog", "dog", "dog", "dog", "dog", "dog", "cat", "cat", "bird")

我将其转换为与数据框中其他向量一起使用的因子:

animalFactor <- as.factor(animals)

我现在想创建一个直方图,显示y轴上每个变量的频率,x轴上每个因子的名称,每个因子包含一个条形。我尝试这段代码:

hist(table(animalFactor), freq=TRUE, xlab = levels(animalFactor), ylab = "Frequencies")

输出绝对不像我期望的那样。抛开标签问题,我似乎无法弄清楚如何按类别创建简单的频率直方图。

6 个答案:

答案 0 :(得分:58)

好像你想要barplot(prop.table(table(animals)))

enter image description here

然而,这不是直方图。

答案 1 :(得分:18)

如果您想在ggplot中执行此操作,则会对geom_histogram()进行API更改,从而导致错误:https://github.com/hadley/ggplot2/issues/1465

要解决此问题,请使用geom_bar()

animals <- c("cat", "dog",  "dog", "dog", "dog", "dog", "dog", "dog", "cat", "cat", "bird")

library(ggplot2)
# counts
ggplot(data.frame(animals), aes(x=animals)) +
  geom_bar()

enter image description here

答案 2 :(得分:13)

您获得意外结果的原因是hist(...)计算数字向量的分布。在您的代码中,table(animalFactor)的行为类似于具有三个元素的数字向量:1,3,7。因此hist(...)绘制1的数量(1),3的数量(1)和数字7的(1)。 @Roland的解决方案是最简单的。

以下是使用ggplot

执行此操作的方法
library(ggplot2)
ggp <- ggplot(data.frame(animals),aes(x=animals))
# counts
ggp + geom_histogram(fill="lightgreen")
# proportion
ggp + geom_histogram(fill="lightblue",aes(y=..count../sum(..count..)))

在上面的代码中使用animalFactor代替animals可以获得完全相同的结果。

答案 3 :(得分:2)

国家/地区是一个分类变量,我想查看数据集中存在多少个国家/地区。换句话说,每个国家/地区有多少记录/与会者

barplot(summary(df$Country))

答案 4 :(得分:1)

数据因子可用作绘图函数的输入。

这里给出了类似问题的答案: https://stat.ethz.ch/pipermail/r-help/2010-December/261873.html

 x=sample(c("Richard", "Minnie", "Albert", "Helen", "Joe", "Kingston"),  
 50, replace=T)
 x=as.factor(x)
 plot(x)

答案 5 :(得分:0)

您也可以使用import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo Custom Slider', debugShowCheckedModeBanner: false, theme: ThemeData( brightness: Brightness.dark, primarySwatch: Colors.blue, ), home: MyHomePage(title: 'Flutter Demo Custom Slider'), ); } } class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => _MyHomePageState(); } class tickMark_Line_Heigth extends SliderTickMarkShape { final double alturaTick; final double anchuraTick = 3; const tickMark_Line_Heigth(this.alturaTick); @override Size getPreferredSize({SliderThemeData sliderTheme, bool isEnabled}) { return Size.fromRadius(alturaTick); } @override void paint(PaintingContext context, Offset center, {RenderBox parentBox, SliderThemeData sliderTheme, Animation<double> enableAnimation, Offset thumbCenter, bool isEnabled, TextDirection textDirection}) { final Canvas canvas = context.canvas; final paint = Paint() ..color = Colors.yellowAccent ..style = PaintingStyle.fill; Offset centro = Offset(center.dx + 2, center.dy - alturaTick * 2); Rect puntos = centro & Size(anchuraTick, alturaTick * 4); canvas.drawRect(puntos, paint); } } class _MyHomePageState extends State<MyHomePage> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Center( // Center is a layout widget. It takes a single child and positions it // in the middle of the parent. child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Expanded( child: slider(0), flex: 1, ), Expanded( child: slider(1), flex: 1, ), Expanded( child: slider(2), flex: 1, ), Expanded( child: slider(3), flex: 1, ), Expanded( child: slider(4), flex: 1, ), Expanded( child: slider(5), flex: 1, ), Expanded( child: slider(6), flex: 1, ), Expanded( child: slider(7), flex: 1, ), ], ), ), floatingActionButton: visibleActionButton ? FloatingActionButton.extended( onPressed: () { // Add your onPressed code here! }, label: Row( children: <Widget>[ Column( children: <Widget>[ Text('Slide',style: TextStyle(fontSize: 10)), Text('$numSlider',style: TextStyle(fontSize: 10)), ], ), Text('$valueSlider',style: TextStyle(fontSize: 30)), ], ), backgroundColor: colorSlider(valueSlider), ) : null, floatingActionButtonLocation: FloatingActionButtonLocation.endTop, ); } var valuesSlider = [0, 0, 0, 0, 0, 0, 0, 0]; int valueSlider = 0; int numSlider = 0; bool visibleActionButton = false; Color colorSlider(valor) { Color color; switch (valor) { case 0: case 1: color = Colors.green; break; case 2: case 3: color = Colors.orange; break; default: color = Colors.red; } return color; } Widget slider(num) { return SliderTheme( data: SliderTheme.of(context).copyWith( trackHeight: 18, minThumbSeparation: 1, tickMarkShape: tickMark_Line_Heigth(4)), child: Slider( value: valuesSlider[num].toDouble(), min: 0, max: 5, divisions: 5, activeColor: colorSlider(valuesSlider[num]), inactiveColor: Colors.lightBlue, label: '${valuesSlider[num]}', onChangeStart: (newValue) { setState(() { valueSlider = newValue.round(); numSlider = num + 1; visibleActionButton = true; }); }, onChangeEnd: (newValue) { setState(() { valueSlider = 0; visibleActionButton = false; }); }, onChanged: (newValue) { setState(() { valuesSlider[num] = newValue.round(); valueSlider = newValue.round(); }); }, ), ); } }