Put the legend of pandas bar plot with secondary y axis in front of bars

2024/11/10 20:41:27

I have a pandas DataFrame with a secondary y axis and I need a bar plot with the legend in front of the bars. Currently, one set of bars is in front of the legend. If possible, I would also like to place the legend in the lower-left corner. Any ideas appreciated!

I have attempted to set the legend=false and add a custom legend, but it has the same issue. I've tried reordering the columns but there's no way to clear a space for this on the chart.

import pandas as pd
import matplotlib.pyplot as pltdf_y = pd.DataFrame([['jade',12,800],['lime',12,801],['leaf',12,802], ['puke',12,800]], columns=['Territory','Cuisines','Restaurants'])
df_y.set_index('Territory', inplace=True)plt.figure()
ax=df_y.plot(kind='bar', secondary_y=['Restaurants'])
ax.set_ylabel('Cuisines')
ax.right_ax.set_ylabel('Restaurants')
plt.show()

One set of bars appears behind the legend, and one set appears in front of the legend. The link below goes to an image showing the problem. Thank you!

link to image

Answer

You can create the legend yourself.

Use the color cycler to get the colors correct when zipped with the columns. Make sure to set legend=False in the barplot. loc=3 is the lower left.

import matplotlib.patches as mpatches
import matplotlib.pyplot as pltfig, ax = plt.subplots()
df_y.plot(kind='bar', secondary_y=['Restaurants'], legend=False, ax=ax)
ax.set_ylabel('Cuisines')
ax.right_ax.set_ylabel('Restaurants')L = [mpatches.Patch(color=c, label=col) for col,c in zip(df_y.columns, plt.rcParams['axes.prop_cycle'].by_key()['color'])]plt.legend(handles=L, loc=3)
plt.show()

enter image description here

https://en.xdnf.cn/q/72307.html

Related Q&A

Printing floats with a specific number of zeros

I know how to control the number of decimals, but how do I control the number of zeros specifically?For example:104.06250000 -> 104.0625 119.00000 -> 119.0 72.000000 -> 72.0

How do I make a matplotlib scatter plot square?

In gnuplot I can do this to get a square plot:set size squareWhat is the equivalent in matplotlib? I have tried this:import matplotlib matplotlib.use(Agg) import matplotlib.pyplot as plt plt.rcParams[…

Efficiently determining if a business is open or not based on store hours

Given a time (eg. currently 4:24pm on Tuesday), Id like to be able to select all businesses that are currently open out of a set of businesses. I have the open and close times for every business for ev…

parsing .xsd in python

I need to parse a file .xsd in Python as i would parse an XML. I am using libxml2. I have to parse an xsd that look as follow: <xs:complexType name="ClassType"> <xs:sequence><x…

How to get the params from a saved XGBoost model

Im trying to train a XGBoost model using the params below: xgb_params = {objective: binary:logistic,eval_metric: auc,lambda: 0.8,alpha: 0.4,max_depth: 10,max_delta_step: 1,verbose: True }Since my input…

Reverse Label Encoding giving error

I label encoded my categorical data into numerical data using label encoderdata[Resi] = LabelEncoder().fit_transform(data[Resi])But I when I try to find how they are mapped internally usinglist(LabelEn…

how to check if a value exists in a dataframe

hi I am trying to get the column name of a dataframe which contains a specific word,eg: i have a dataframe,NA good employee Not available best employer not required well mana…

Do something every time a module is imported

Is there a way to do something (like print "funkymodule imported" for example) every time a module is imported from any other module? Not only the first time its imported to the runtime or r…

Unit Testing Interfaces in Python

I am currently learning python in preperation for a class over the summer and have gotten started by implementing different types of heaps and priority based data structures.I began to write a unit tes…

Python Pandas average based on condition into new column

I have a pandas dataframe containing the following data:matchID server court speed 1 1 A 100 1 2 D 200 1 3 D 300 1 …