Is there a way to create a combined bar and line plot on a single graph with separate Y axes?

I have two sets of data that share a common index, and I would like to display the first set as a barplot and the second set as a line plot on the same graph. Currently, I am using a method similar to the one shown below.

ax = pt.a.plot(alpha = .75, kind = 'bar')
ax2 = ax.twinx()
ax2.plot(ax.get_xticks(), pt.b.values, alpha = .75, color = 'r')

The resulting graph looks something like this:

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

While the image is visually appealing, it's not quite perfect. The issue I'm facing is that ax.twinx() appears to overlay a new canvas on top of the existing one, causing white lines to be visible over the barplot.

Is there a way to create this plot without these unwanted white lines?

Answer №1

If you want to create a dual y-axis plot with seaborn, you can utilize the twinx() method. This allows you to have separate y-axes for different plots such as lineplot and barplot. To customize the style of the plot (default is darkgrid), you can use the set_style method to choose a different theme. Setting style=None will give you a white background without gridlines, or you can experiment with other themes like whitegrid. If you need more control over the gridlines, you can adjust them at the axis level using ax2.grid(False).

import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns

matplotlib.rc_file_defaults()
ax1 = sns.set_style(style=None, rc=None )

fig, ax1 = plt.subplots(figsize=(12,6))

sns.lineplot(data = df['y_var_1'], marker='o', sort = False, ax=ax1)
ax2 = ax1.twinx()

sns.barplot(data = df, x='x_var', y='y_var_2', alpha=0.5, ax=ax2)

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

Answer №2

To remove the grid lines of the second axis, simply add ax2.grid(False) to your code. Keep in mind that the y-ticks of the second axis will not align with those of the first y-axis, as shown below:

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

fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot(pd.Series(np.random.uniform(0,1,size=10)), color='g')
ax2 = ax1.twinx()
ax2.plot(pd.Series(np.random.uniform(0,17,size=10)), color='r')
ax2.grid(False)
plt.show()

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

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

The Selenium test functions correctly in the production environment, however it encounters issues when run

I am facing an issue with my Vue.js application while writing Selenium tests. The test passes when run against the deployed production version of the app, but fails when run against a local version. When running the app locally, it is not from a build, bu ...

The Django query for Freelancers using get() resulted in three matches being returned instead of just one

I encountered an issue when trying to assign a freelancer to a specific gig, as the get() method returned more than one Freelancer - in fact, it returned 3! I attempted to retrieve the logged-in freelancer who is creating the gig by using freelancer = get_ ...

What can I do to alter this Fibonacci Sequence Challenge?

I'm currently exploring ways to modify the code below in order to address the given question. My goal is to enhance the functionality so that I can also take 3 steps at a time, in addition to 1 or 2 steps. You are faced with a ladder consisting of N ...

Encountering a problem while trying to log into Instagram with selenium, receiving the error message "We had trouble logging you in to Instagram."

I have been working on a code to scrape Instagram, search, and analyze posts and likes. My bot was functioning perfectly fine until yesterday when it suddenly stopped being able to log in. I've tried various troubleshooting methods: Logging out from ...

Searching for specific information within a JSON file (across multiple lines)

Currently, I am working on extracting specific lines of data from a JSON file. It seems that using grep in this particular scenario might be the way to go, but I could use some guidance. Below is an example of the JSON data: [ 'vlans VLAN10 vlan-id 1 ...

Update the title of the website article with the article's title when saving a screenshot with

I am currently attempting to capture partial screenshots for each article from this particular website. I have successfully identified the element using the snippet provided below. <div id="post-4474417" class="post-box " data-permalink="https://hyp ...

Exploring the Django-Rest-Swagger documentation for effectively documenting the API within Django Rest Framework

I am currently exploring ways to document my API using the swagger generator tool called django-rest-swagger with DRF. At the moment, I am creating views by extending the rest_framework.views.APIView. I prefer not to use viewsets or serializers for writi ...

Having trouble with Selenium Chromedriver failing to download to the designated folder

I am currently attempting to retrieve some data from the FanGraphs Leaderboards using the selenium library. Initially, I was using Firefox for this task, but due to Chrome being faster, I decided to make the switch. While things worked smoothly with Firefo ...

Adjusting attributes within a weka.core.dataset.Instances entity

Currently utilizing python-weka-wrapper3 to handle an arff dataset that has been loaded. kc1_class_arff = arff_loader(DATA_PATH, "/kc1_class.arff") The final column in this particular dataset goes by the name of NUMDEFECTS and contains float val ...

A more Pythonic approach to managing JSON responses in Python 2.7

Currently, I am using Python 2.7 to fetch JSON data from an API. Here is the code snippet I have been working on: import urllib2 URL = "www.website.com/api/" response = urllib2.urlopen(URL) data = json.load(response) my_variable = data['location&apo ...

Step-by-step guide on correctly plotting the image after converting it to an array using the img_to_array function

I'm trying to figure out how to plot an image that has been converted into an array using keras.preprocessing.image.img_to_array. Here's my approach. To provide a simple example, I downloaded a picture of a duck from the internet: import urllib ...

reducing my code by using parentheses for both 'and' and 'or' outcomes

What is the best way to simplify this code snippet? if (a+b+c == 1000 and a**2 + b**2 == c**2) or (a+b+c == 1000 and a**2 + c**2 == b**2) or (a+b+c == 1000 and b**2 + c**2 == a**2) into: if a+b+c == 1000 and (a**2 + b**2 == c**2 or a**2 + c**2 == b**2 o ...

Working with JSON responses from Google search in Python using the Requests library. Utilizing regex for

I need to convert the initial response into a valid JSON format, which I can do but in a somewhat messy way. Here's the original response: // API callback google.search.Search.apiary2387({ "cursor": { "currentPageIndex": 0, "estimatedResultCoun ...

What are the best methods for converting LSTMs into vectors?

I'm currently puzzled by the concept of an LSTM layer having a specific number of cells, like 50 in this example. Let's analyze the following LSTM block excerpted from a fascinating blog post: https://i.stack.imgur.com/y91nY.png Assuming my inp ...

What is the reason behind receiving the alert message "Received 'WebElement' instead of 'collections.Iterable' as expected" at times?

When using Selenium's find_element(By.XPATH, "//tag[@class='classname']" to iterate over elements of specific classes, Pycharm sometimes shows a warning: "Expected 'collections.Iterable', got 'WebElement' i ...

"Locating Python on Apple M1 Chips: A Comprehensive

On my Apple Silicon (ARM64) machine, Python gets installed as python3 instead of python. This causes issues with a node.js project that has dependencies requiring python and pip. The builds fail because they cannot locate python. python3 is located in th ...

Using Python and Selenium to trigger a 2FA email on the Palo Alto website

I'm currently working on a script to download a file from the Palo Alto Networks website. Everything is going smoothly so far - I've managed to input the username and password successfully. However, I'm encountering an issue when it comes to ...

Leveraging Python Selenium for extracting text containing Russian characters

When extracting text from a div using the selenium .text attribute like this: message_text = message.find_element_by_class_name("im_msg_text").text The output you may see when trying to print message_text is: 'message_text': u'\u043a ...

Execute a Python script on multiple files located in various directories

I'm dealing with a Python script that utilizes two separate Excel files for data processing. These files are referenced in the same manner within the script but are stored in different folders. The script specifies from which folders to retrieve the f ...

Selenium code refuses to shut down

Why is the following code not terminating? import selenium from selenium.webdriver.common.keys import Keys browser = selenium.webdriver.Firefox() browser.get("http://www.quora.com/physics") element = browser.find_element_by_class_name("cancel") #ele=el ...