简体   繁体   English

直接从数据框熊猫对象中带有颜色条的水平条形图

[英]horizontal bar chart with color bar directly from a dataframe pandas object

I have the below code and I am wondering if I can produce a horizontal bar chart plot where the bars change colour horizontally (overtime in my case) according to a given colour map directly from a data frame object. 我有下面的代码,我想知道是否可以生成水平条形图,其中条形直接根据数据框对象中的给定颜色映射水平地改变颜色(在我的情况下是超时)。

from matplotlib import pyplot as plt
from matplotlib import cm
import pandas as pd
import numpy as np

# generate dataframe
df = pd.DataFrame(np.random.randn(1000, 4), index=pd.date_range('1/1/2000', periods=ndays), columns=list('ABCD'))
df = df.cumsum()

# plot dataframe
df.plot(figsize=(10,5))

# TODO
# make a plot with four horizontal bars each for one column (A, B, C, D)
# the bars represent the time variation and thus should change colour according to the values in the ABCD columns mapped to cmap colour map

df_plot_with_line

I also include below a temporary solution using scatter plot for the purpose of visualisation what I aim for. 我还在下面提供了一个使用散点图的临时解决方案,用于可视化我的目标。

# this is what I would like plot to look like
# I use plt.scatter to show
fig = plt.figure(figsize=(15,2))
ax = fig.add_subplot(111)
cmap = cm.gnuplot
ax.scatter(x=df.index, y=[0]*df.A.shape[0], c=df.A, cmap=cmap)
ax.scatter(x=df.index, y=[1]*df.A.shape[0], c=df.B, cmap=cmap)
ax.scatter(x=df.index, y=[2]*df.A.shape[0], c=df.C, cmap=cmap)
cax = ax.scatter(x=df.index, y=[3]*df.A.shape[0], c=df.D, cmap=cmap)

# vertical color bar
clim = cax.get_clim()
cbar = fig.colorbar(cax, ticks=[min(clim),np.mean(clim),max(clim)], orientation='vertical')
cbar.ax.set_xticklabels(['Low', 'Medium', 'High'])

my_current_solution

Note: The question is not about scatter plot but if and how to make the result obtain with my current solution directly from the data frame object. 注意:问题不是关于散点图,而是关于是否以及如何使结果直接从数据框对象中以当前解决方案获取。

You can kind of do this through pandas, but it is really ugly. 您可以通过熊猫来做到这一点,但这确实很丑。 You need to make new columns just for scatter plotting, and then pass the color argument a list of colors based on the actual data. 您需要为散点图创建新的列,然后将color参数基于实际数据传递给颜色列表。

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

df = pd.DataFrame(np.random.randn(1000, 4), index=pd.date_range('1/1/2000', periods=1000), 
                  columns=list('ABCD')).cumsum()

# create color normalizer
cnormer = colors.Normalize(df.min().min(), df.max().max())

# add new columns for the scatter plot
df['i'] = np.arange(1000)
for x in range(4):
    df['z{}'.format(x)] = x

# create an axis to plot on
fig, ax = plt.subplots(1,1,figsize=(10,3))

# make scatter plots
for x in range(4):
    df.plot(x='i', y='z{}'.format(x), kind='scatter', marker='o', edgecolor='none', 
            c=plt.cm.viridis(cnormer(df.iloc[:,x])), ax=ax)

You would still need to reformat the labels and ticks. 您仍然需要重新格式化标签和刻度。

在此处输入图片说明

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

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