python画对比双色柱状图_如何在Python中绘制一列被另一列着色的柱状图?
我有一个数据集,其中包含3列,标题为Gender(要么M要么F)、House(要么A要么B要么C)和Indicator(要么0要么1)。我想绘制按性别划分的房屋直方图。这是我的代码:import pandas as pd
df = pd.read_csv('dataset.csv', usecols=['House','Gender','Indicator')
A = df[df['House']=='A']
A = pd.DataFrame(A, columns=['Indicator', 'Gender'])
这将正确地导入房屋A的各个性别的价值,如其内容所示:print(A)
Indicator Gender
0 1 Male
1 1 Male
2 1 Male
4 1 Female
7 1 Male
8 1 Male
11 1 Male
14 1 Male
17 1 Male
18 1 Female
19 1 Female
20 1 Female
21 1 Male
24 1 Male
26 1 Female
27 1 Male
... ... ...
现在,当我想用我在MATLAB中的方法绘制按性别着色的直方图时,它会给出一个错误:import matplotlib.pyplot as plt
plt.hist(A)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
in ()
----> 1 plt.hist(A)
~\AppData\Local\Continuum\anaconda3\lib\site-packages\matplotlib\pyplot.py in hist(x, bins, range, density, weights, cumulative, bottom, histtype, align, orientation, rwidth, log, color, label, stacked, normed, hold, data, **kwargs)
3130 histtype=histtype, align=align, orientation=orientation,
3131 rwidth=rwidth, log=log, color=color, label=label,
-> 3132 stacked=stacked, normed=normed, data=data, **kwargs)
3133 finally:
3134 ax._hold = washold
~\AppData\Local\Continuum\anaconda3\lib\site-packages\matplotlib\__init__.py in inner(ax, *args, **kwargs)
1853 "the Matplotlib list!)" % (label_namer, func.__name__),
1854 RuntimeWarning, stacklevel=2)
-> 1855 return func(ax, *args, **kwargs)
1856
1857 inner.__doc__ = _add_data_doc(inner.__doc__,
~\AppData\Local\Continuum\anaconda3\lib\site-packages\matplotlib\axes\_axes.py in hist(***failed resolving arguments***)
6512 for xi in x:
6513 if len(xi) > 0:
-> 6514 xmin = min(xmin, xi.min())
6515 xmax = max(xmax, xi.max())
6516 bin_range = (xmin, xmax)
~\AppData\Local\Continuum\anaconda3\lib\site-packages\numpy\core\_methods.py in _amin(a, axis, out, keepdims)
27
28 def _amin(a, axis=None, out=None, keepdims=False):
---> 29 return umr_minimum(a, axis, None, out, keepdims)
30
31 def _sum(a, axis=None, dtype=None, out=None, keepdims=False):
TypeError: '<=' not supported between instances of 'int' and 'str'
似乎我们需要指定要制作直方图的确切列。它不能自动理解(不像MATLAB)它需要根据另一列进行着色。因此,执行以下绘制柱状图的操作,但没有颜色指示性别:plt.hist(A['Indicator'])
那么,我该如何制作一个堆积的直方图,或者一个按性别排列的直方图呢?类似这样,除了在x=0和x=1时每个指示器只有2条:x = np.random.randn(1000, 2)
colors = ['red', 'green']
plt.hist(x, color=colors)
plt.legend(['Male', 'Female'])
plt.title('Male and Female indicator by gender')
我试图通过将两个dataframe列复制到列表的两个列中,然后尝试绘制直方图来模拟上述情况:y=[]
y[0] = A[A['Gender'=='M']].tolist()
y[1] = A[A['Gender'=='F']].tolist()
plt.hist(y)
但这会产生以下错误:KeyError Traceback (most recent call last)
~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
3062 try:
-> 3063 return self._engine.get_loc(key)
3064 except KeyError:
pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
KeyError: False
During handling of the above exception, another exception occurred:
KeyError Traceback (most recent call last)
in ()
2 A= pd.DataFrame(A, columns=['Indicator', 'Gender'])
3 y=[]
----> 4 y[0] = A[A['Gender'=='M']].tolist()
5 y[1] = A[A['Gender'=='F']].tolist()
6 plt.hist(y)
~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\frame.py in __getitem__(self, key)
2683 return self._getitem_multilevel(key)
2684 else:
-> 2685 return self._getitem_column(key)
2686
2687 def _getitem_column(self, key):
~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\frame.py in _getitem_column(self, key)
2690 # get column
2691 if self.columns.is_unique:
-> 2692 return self._get_item_cache(key)
2693
2694 # duplicate columns & possible reduce dimensionality
~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\generic.py in _get_item_cache(self, item)
2484 res = cache.get(item)
2485 if res is None:
-> 2486 values = self._data.get(item)
2487 res = self._box_item_values(item, values)
2488 cache[item] = res
~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\internals.py in get(self, item, fastpath)
4113
4114 if not isna(item):
-> 4115 loc = self.items.get_loc(item)
4116 else:
4117 indexer = np.arange(len(self.items))[isna(self.items)]
~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
3063 return self._engine.get_loc(key)
3064 except KeyError:
-> 3065 return self._engine.get_loc(self._maybe_cast_indexer(key))
3066
3067 indexer = self.get_indexer([key], method=method, tolerance=tolerance)
pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
KeyError: False
python画对比双色柱状图_如何在Python中绘制一列被另一列着色的柱状图?相关推荐
- python画人脸编程怎么写_如何在Python(GUI)中绘制人脸
首先让我以我只使用过Java作为开场白,所以Python对我来说确实是个新手.结果,我甚至在检查我的程序是否工作时遇到了很多麻烦.令人沮丧.(顺便说一下,我正在使用python2.7) 我不知道怎么画 ...
- python画图表用引用数据_如何在python pandas中对数据帧使用按引用传递
关于巫术的事很抱歉.在 问题是工作线程必须具有唯一的数据帧实例.几乎所有对Pandas数据帧进行切片或分块的尝试都会导致原始数据帧的别名.这些别名仍将导致工作线程之间的资源争用.在 有两件事可以提高性 ...
- matlab怎么画三维坐标的二维图,excel怎么画二维坐标表格图(如何在excel中绘制三维坐标系?)...
在excle中怎么把二维图形变成三维图形 你说的是图表吗,如果是的话就这样操作 excel2007以上版本:选中图表-点击设计选项卡-最左面有更改图表类型-选择合适的类型-确定 excel2003也是 ...
- 用python画六边形并填充颜色_如何用Python,画一个正多边形,长度和颜色还是任意的!...
Python画基本形状,要用到自带的turtle库,这是个简单绘图的入门小工具. 任务设定如上,下面来一点点拆解它. 从键盘获取用户输入的边数. 画笔形状由原来的三角形,改为海龟形状. 长度随机产生, ...
- 用python画小猪佩奇的编码_如何用python绘制小猪佩奇-python绘图教程图文讲解
原标题:如何用python绘制小猪佩奇-python绘图教程图文讲解 如何运用python来绘制小猪佩奇呢?通过几道简单的python代码即可让你绘制出小猪佩奇,话不多说,直接上代码. 用python ...
- python中用什么函数读取字符串_如何在Python中获得函数名作为字符串?
在Python中,如何在不调用函数的情况下以字符串的形式获得函数名? 1 2 3 4def my_function(): pass print get_function_name_as_string( ...
- 如何在ppt中生成柱状图_如何在ppt中制作柱形图和曲线图
如何在 ppt 中制作柱形图和曲线图 篇一: ppt 柱状图与线状同在的操作 用 excel2010 制作双轴柱线复合图表 就是要用 excel2010 做一个这样的图表: excel2010 中,左 ...
- python set 排序_python set 排序_如何在Python中使用sorted()和sort()
点击"蓝字"关注我们 ?"Python基础知识" 大卫·丰达科夫斯基 著 18财税3班 李潇潇 译 日期:2019年5月6日 一. 使用sorted() ...
- python如何定义一个空变量_如何在python中定义自由变量? - python
python doc中的本地/全局/自由变量定义: 如果名称绑定在块中,则除非声明为非本地,否则它是该块的局部变量.如果在模块级别绑定了名称,则该名称为全局变量. (模块代码块的变量是局部变量和全局变 ...
最新文章
- linux 进程(二) --- 进程的创建及相关api
- esp32cam与下载板的实际有效接线图
- 25 个精美的后台管理界面模板和布局
- JSON中单双引号的处理
- C# 序列化技术详解《转》
- win7开机动画_仍有4亿中国用户死守win7 你为何还不选择升级?
- Java static、 final修饰符
- oracle 返回hashmap,解决:oracle+myBatis ResultMap 类型为 map 时返回结果中存在 timestamp 时使用 jackson 转 json 报错...
- Maven运行时异常java.lang.UnsupportedClassVersionError的解决方案
- javascript--this机制
- 上一周,小白的我试着搭建了两个个人博客:在github和openshift上
- android调用Camera.open方法报错“Too many cameras already open”
- OPC 0x00000005 问题
- Codeforces Round #439 (Div. 2) E. The Untended Antiquity(二维BIT)
- 看了这篇Docker指令详解,网友直呼:我收藏了你呢?
- 计算机取证(Computer Forensic)
- 系统集成特一级资质标准
- 虚拟化服务器里的cpu是什么型号的,VMware虚拟化CPU型号不一样,在集群中如何进行VMotion?...
- 美国科技博客网:改变世界15种技术
- 7亿美元,京东上市前的最后一块踏板?
热门文章
- WinDbg CDB
- 信息安全知识分享—PKI技术
- 微信小程序:地图导航功能实现完整源代码附效果图,讲解
- 机器学习领域的五大流派
- 十五、Fiddler抓包工具详细教程 — Fiddler抓包HTTPS请求(二)
- 43. Systemd的Unit配置详解,unit文件位置,优先级,unit类型,unit文件字段详解,Unit/Service/Install字段,添加mysql服务等例子
- 关于:使用 nslookup 验证加入域所需的 SRV 记录
- 赞爆!全国计算机专业数据库系统工程师考试指定教程(第三版)
- 彩色空间-CIELAB和LAB的关系
- WebBrower打开Office2007文件