The functionality of hatches in Matplotlib cycler is not functioning properly

Consider the sample code snippet below:

%matplotlib notebook

import matplotlib.pyplot as plt
from cycler import cycler

bar_cycler = (cycler(color=["#E69F00", "#56B4E9"]) +
             cycler(hatch=["/" , "o"]))

plt.rc("axes", prop_cycle=bar_cycler)


data = {
  "calories": [420, 380, 390],
  "duration": [50, 40, 45]
}

df = pd.DataFrame(data)

df.plot(stacked=True, kind='bar')

The above code generates a plot that successfully sets the colors but fails to implement hatching.

To address this issue and make cyclers work properly with hatching, follow the guidelines provided in the image reference link.

How can I effectively combine cyclers and hatching in my plots?

Answer №1

There may be limitations on using the hatch feature with certain types of plots, which can pose a problem.

However, it is possible to achieve the desired plot by utilizing two separate instances of the bar() function.

import matplotlib.pyplot as plt
import pandas as pd

data = {
  "calories": [420, 380, 390],
  "duration": [50, 40, 45]
}

df = pd.DataFrame(data)

fig, ax = plt.subplots()
ax.bar(["1","2","3"], df['calories'], hatch='/', color="#E69F00")
ax.bar(["1" ,"2","3"], df['duration'], hatch='*', color="#56B4E9", bottom=df['calories'])

plt.show()

https://i.stack.imgur.com/KPH3m.png


For further information, refer to the Matplotlib documentation on Stacked bar chart, Hatch demo, and Hatch style reference.


EDIT:

A different approach involves utilizing two bar() functions or setting the hatch attribute after drawing the bars.

Refer to this Stack Overflow thread for more insights.

In another version, the use of itertools.cycle proves advantageous due to the nested loops required when dealing with multiple Rectangles in a BarContainer.

import pandas as pd
import matplotlib.pyplot as plt
from cycler import cycler

bar_cycler = cycler(color=["#E69F00", "#56B4E9"])
             
plt.rc("axes", prop_cycle=bar_cycler)

data = {
  "calories": [420, 380, 390],
  "duration": [50, 40, 45]
}

df = pd.DataFrame(data)

ax = df.plot(stacked=True, kind='bar')

# ---

import itertools

cycle_hatch = itertools.cycle(["/" , "o"])

for container, hatch in zip(ax.containers, cycle_hatch):
    for item in container.patches:
        item.set_hatch(hatch)
    
# ---     

plt.show()

EDIT:

Another similar query involved setting different hatching styles for each Rectangle within a BarContainer.

More details are available in this Stack Overflow post.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Quick explanation of the concept of "matrix multiplication" using Python

I am looking to redefine matrix multiplication by having each constant represented as another array, which will be convolved together instead of simply multiplying. Check out the image I created to better illustrate my concept: https://i.stack.imgur.com/p ...

There is nothing like Python Bottle when it comes to parsing JSON data from

In my React code, I have the following: const payload = { x : x, y : y } fetch("http://localhost:8080/update_game", { method: "POST", body: JSON.stringify(payload)}) And in Python, I have this implementation: @post(&ap ...

Dealing with large file sizes in Python with Azure Function App Blob Trigger

Currently, I am utilizing Azure function apps (Python) with a blob trigger to handle CSV processing and transferring the records to an event hub. The existing code is functional for files up to 50 rows, which was developed by following standard documentati ...

Combining Graphical User Interface with Scripting

I am facing a challenge while trying to integrate two separate scripts, one with a GUI and the other being a bot script. Individually, both scripts run as expected but when combined, the bot function gets called immediately without displaying the user in ...

What is the best way to perform vectorized calculations on a pandas dataframe, replacing values with the data from the previous row if a certain condition is not satisfied

My current approach involves using a for loop with a conditional statement that triggers a calculation and updates the column in a dataframe when true. However, if the condition is not met, the data from the previous row is carried over to the new row. He ...

Preserving the HTML tag structure in lxml - What is the best method?

Here is a url link that I have: I am attempting to extract the main body content of this news page using LXML with xpath: //article, however it seems to include content beyond the body tag As LXML modifies the HTML structure upon initialization, I am see ...

Guide to creating an HTML table with bokeh

As a newcomer to Bokeh, I've been searching through the documentation for examples but haven't come across an in-built method for creating tables. I have some data that I need to display in tabular format and was wondering what the most straightf ...

Exploring the process of file documentation using the statement 'import * from x'

Is it possible to utilize sphinx's automodule:: and other automatic features to document modules that contain from x import * statements without including all of the documentation from the imported modules? UPDATE: According to mzjn's observatio ...

Each start URL in Scrapy generates its own unique CSV file as output

I need help figuring out how to output multiple CSV files for each start_url in my Scrapy pipeline. Currently, I am only able to generate one file with information from all the URLs. pipeline.py class CSVPipeline(object): def __init__(self): self.fi ...

Customize Bokeh DataTable cell colors using unique range values for each cell

I am working with a bokeh data table that displays the concentration measurements for three different QC samples: low concentration, medium concentration, and high concentration. Unnamed: 0 run 9Be 45Sc 51V 52Cr 55Mn........ QC Low Mean ...

Python integration with Azure Durable Functions may encounter issues causing interruptions or delays in processing tasks, resulting in instances getting stuck in an

When implementing an Azure Durable Function in Python on the consumption plan, I encountered an issue where the function would fail to execute successfully after running it around 2000 times a day for a couple of weeks. The process involves fetching data f ...

Experiencing difficulties when attempting to deploy script to AWS Lambda

My current challenge involves executing a script that utilizes Selenium and specifically webdriver. driver = webdriver.Firefox(executable_path='numpy-test/geckodriver', options=options, service_log_path ='/dev/null') The problem I am ...

Error message displayed by Django-ratings: "The rating value should be a Rating instance, not '100"

I'm having trouble sorting a group of model objects by rating using the Django-ratings app. I've created an order_by function in my view that is functioning correctly, except when it comes to sorting by the rating field. In this case, I am receiv ...

Unpacking Key-Value Pairs in Python

I am developing a software program where I have a dictionary that contains only one key and one value. My goal is to assign the key to a variable named 'key' and the value to a variable named 'value.' Here is the relevant code snippet: ...

Access the IMDb platform using Selenium and Python

My attempt to log in to "IMDB" using Python Selenium is not working correctly because it requires passing a captcha and sending a 2-step verification code. Interestingly, logging in with your own browser does not require filling out the captcha. Screensho ...

Finding the "send item" button in Outlook Office with the help of Chromedriver

Hey there, I'm having some trouble clicking on the "New Group" option in the office365 menu using chromedriver with selenium. Unfortunately, when I try to run the script I created, it doesn't seem to be working as expected. Here is a screenshot s ...

The power trio: Python, Numpy, and OLS working together

Although the code provided is close to what I need, there is a minor adjustment required. I aim to replace c[1] with c[1:] in order to perform regression against all the x variables instead of just one. However, upon making this change and adding the neces ...

What seems to be the issue with this json.load function call?

I wrote the following Python 3 code snippet: import json with open('calldb.json', 'r') as G: data = json.load(G) print(data) Accompanied by this JSON file: [ { "n": { "identity": 0, "labels": [ ...

What is the mechanism by which Scikit-Learn's .fit() method transfers data to .predict()?

I am currently exploring the connection between the sklearn's .fit() method and the .predict() method. I have not been able to find a comprehensive answer to this question on other online forums, although similar topics have been discussed (see here). ...

Unable to select the element transitioning from [display:none] to [display:block] in the bootstrap datetimepicker

I'm facing an issue with a bootstrap DateTime picker on my page. The calendar icon allows me to show the popup, which changes from display: none; to display: block; However, when I click the button labeled 今日, I encounter an error: selenium.comm ...