简体   繁体   English

用垂直线绘制熊猫数据框

[英]Plot a pandas dataframe with vertical lines

I want to plot a dataframe where each data point is not represented as a point but a vertical line from the zero axis like : 我想绘制一个数据框,其中每个数据点都不表示为点,而是从零轴开始的垂直线,例如:

df['A'].plot(style='xxx') DF [ 'A']。图(风格= 'XXX')

where xxx is the style I need. xxx是我需要的样式。

Also ideally i would like to be able to color each bar based on the values in another column in my dataframe. 另外,理想情况下,我希望能够根据我数据框中另一列中的值为每个栏着色。

I precise that my x axis values are numbers and are not equally spaced. 我精确地说,我的x轴值是数字,并且不等距。

The pandas plotting tools are convenient wrappers to matplotlib. 大熊猫绘图工具是matplotlib的便捷包装。 There is no way I know of to get the functionality you want directly via pandas. 我没有办法直接通过熊猫获得所需的功能。

You can get it in a few lines of matplotlib. 您可以在matplotlib的几行中获得它。 Most of the code is to do the colour mapping: 大多数代码是进行颜色映射的:

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.colors as colors
import matplotlib.cm as cmx

#make the dataframe
a = np.random.rand(100)    
b = np.random.ranf(100)    
df = pd.DataFrame({'a': a, 'b': b})

# do the colour mapping
c_norm  = colors.Normalize(vmin=min(df.b), vmax=max(df.b))
scalar_map = cmx.ScalarMappable(norm=c_norm, cmap=plt.get_cmap('jet'))    
color_vals = [scalar_map.to_rgba(val) for val in df.b]

# make the plot
plt.vlines(df.index, np.zeros_like(df.a), df.a, colors=color_vals)

I've used the DataFrame index for the x axis values but there is no reason that you could not use irregularly spaced x values. 我已经将DataFrame索引用于x轴值,但是没有理由不能使用不规则间隔的x值。

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

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