如何在熊猫中添加堆叠条形图阴影? (...或如何在熊猫图与matplotlib中获取BarContainer与AxisSubplot?)

时间:2020-01-03 21:56:25

标签: python pandas matplotlib bar-chart stacked

我有一个使用matplotlib.pyplot.plot()的代码示例可以正常工作,并且我想复制该代码示例以在堆积的条形图上制作阴影线条形段。但是,我一直使用pandas.DataFrame.plot()而不是matplotlib.pyplot.plot()来制作所有其他图形,并且也想在此继续。示例代码返回一个BarContainer对象的元组,而pandas.DataFrame.plot()返回一个AxisSubplot对象,并且我不知道如何在两者之间导航。

关于如何从BarContainer中获取pandas.DataFrame.plot()对象的任何建议,以便我可以使用它们来复制示例?

如果没有,关于如何实现使用pandas.DataFrame.plot()在堆叠条形图上为每个彩色条形段添加阴影的目标的任何建议?

使用我的数据,阴影线将有助于区分相似的颜色,因为我同时具有很多类别和项目,否则结果看上去在外观上是相似的。 (我知道我也可以找到一种方法来绘制简单的东西,但是这样做对我的探索性数据分析很有帮助。)谢谢!


用于填充堆叠条形图的每个彩色条形段的示例工作代码(来自此处:https://matplotlib.org/examples/pylab_examples/hatch_demo.html):

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

fig = plt.figure()
ax2 = fig.add_subplot(111)
bars = ax2.bar(range(1, 5), range(1, 5), color='yellow', ecolor='black') + \
    ax2.bar(range(1, 5), [6] * 4, bottom=range(1, 5), color='green', ecolor='black')

patterns = ('-', '+', 'x', '\\', '*', 'o', 'O', '.')
for bar, pattern in zip(bars, patterns):
    bar.set_hatch(pattern)

enter image description here


我希望我的代码(带有简化的数据)每个彩色条段都有阴影线:

df = pd.DataFrame(np.random.uniform(0,10, size=(5,26)))
df.columns=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
ax = df.plot.barh(stacked=True, width=0.98, figsize=(10,5), cmap='gist_ncar')

enter image description here

1 个答案:

答案 0 :(得分:3)

如何从pandas.DataFrame.plot()中获取BarContainer对象

Axes'容器属性中过滤掉它们

import datetime
import uuid
import time
import json

import msgpack

from kafka import KafkaProducer, KafkaConsumer
from kafka.errors import KafkaError

topic = 'my-topic'
def get_consumer():
    return KafkaConsumer(topic,
            # client_id=str(uuid.uuid1()),
            fetch_max_wait_ms=1,
            group_id='my-group',
            metadata_max_age_ms=10,
            bootstrap_servers=['localhost:9092'],
            value_deserializer=msgpack.loads)

consumer = get_consumer()

producer = KafkaProducer(
        bootstrap_servers=["localhost:9092"],
        value_serializer=msgpack.dumps)

def produce_n(n=100):
    for i in range(n):
        print(i)
        producer.send(topic, value=time.time())
        time.sleep(1)
        producer.flush()

def consume():
    consumer = get_consumer()
    for x in consumer:
        T = time.time()
        dt = T - x.value
        print(x)
        print(f't={x.value} T={T} dt={dt} ms')


在每个BarContainer中的矩形上设置阴影。

>>> import matplotlib as mpl
>>> ax = df.plot.barh(stacked=True, width=0.98, figsize=(10,5), cmap='gist_ncar')
>>> ax.containers[:4]
[<BarContainer object of 5 artists>, <BarContainer object of 5 artists>, <BarContainer object of 5 artists>, <BarContainer object of 5 artists>]
>>> bars = [thing for thing in ax.containers if isinstance(thing,mpl.container.BarContainer)]

以这种方式进行操作将确保您不会抓取不属于酒吧的补丁。


如何获得相同的补丁以在不同项目上以相同的颜色显示

也许在遍历每个栏中的补丁时,检查其facecolorimport itertools patterns = itertools.cycle(('-', '+', 'x', '\\', '*', 'o', 'O', '.')) for bar in bars: for patch in bar: patch.set_hatch(next(patterns)) L = ax.legend() # so hatches will show up in the legend )并维护{facecolor:hatchsymbol}的字典-如果facecolor在字典集中的 填充,否则将获得一个新的填充符号,将其和颜色添加到字典中以设置填充。

patch.get_facecolor

Matplotlib Tutorials是值得的。