I'm creating a stacked bar plot via the code below:
ax = df.plot(
kind="barh",
stacked=True,
width=0.9,
figsize=(10, 11),
colormap="RdYlGn",
xlabel='% Respondents'
);
But the label for the x-axis appears on the y-axis! If I change xlabel to ylabel, the text on the y-axis does not move.
How can I get a label on the x-axis?
I believe this is a bug with pandas version 1.1.5. Upgrading to pandas version 1.5.3 resolved the issue.
Related
I would like to visualize xticklabels suitably by decreasing the frequency of each tick similar to here. Therefore, I found this example as a solution to eliminate the main issue (see below). Therefore, the code I got:
from matplotlib import pyplot as plt, dates as mdates
#Blank subplots
fig, axs = plt.subplots(4, 3, sharex='col', sharey='row', figsize = (6,3), dpi = 140)
#Loop through each chart in the subplot
for count, ax in enumerate(axs.reshape(-1)):
ax.plot(dfN[count]["Tarih"], dfN[count]["PM10"])
ax.xaxis.set_major_locator(mdates.MonthLocator(bymonth=(1, 7)))
ax.xaxis.set_minor_locator(mdates.MonthLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%b'))
for label in ax.get_xticklabels(which='major'):
label.set(rotation=30, horizontalalignment='right')
plt.show()
However, this one throws further issue as below:
The date is not starting with my actual date data. It is starting with 1970.
The main issue:
Any suggestions ? Thanks
I made a line plot using seaborn's relplot and I wanted to customize my legend labels. For some reason when I do this, It creates another legend with out deleting the old one. How do I get rid of the initial legend (The legend with title "Sex")? Also how do I add a legend title to my new legend?
Here is the code I used to generate my plot:
plt.figure(figsize=(12,10))
sns.relplot(x='Year',y = 'cancer/100k pop' , data = dataset_sex,hue="Sex", kind="line",ci=None)
title_string = "Trend of Cancer incidencies by Sex "
plt.xlabel('Years')
plt.title(title_string)
plt.legend(['Men','Women'])
regplot is a figure-level function, and returns a FacetGrid. You can remove its legend via g.legend.remove().
import matplotlib.pyplot as plt
import seaborn as sns
tips = sns.load_dataset("tips")
g = sns.relplot(data=tips, x="total_bill", y="tip", hue="day")
g.legend.remove()
plt.legend(['Jeudi', 'Vendredi', 'Samedi', 'Dimanche'])
plt.show()
This code has been tested with seaborn 0.11. Possibly you'll need to upgrade. To add a title to the legend: plt.legend([...], title='New title').
Note that plt.legend(...) will create the legend inside the last (or only) subplot. If you prefer the figure-level legend next to the plot, to change the legend labels, you can call g.add_legend(labels=[...], title='new title') after having removed the old legend.
PS: Adding legend=False to sns.relplot() will not create the legend entries. So, you'll need to recreate both the legend markers and their labels, while you lost the information of which colors were used.
I have the following codes to create a Seaborn strip plot. I am having a hard time figuring out how to increase the font size of the legend appearing in the plot.
g=sns.stripplot(x="Market", y="Rate", hue="Group",data=myBenchmarkData, jitter=True, size=12, alpha=0.5)
g.axes.set_title("4* Rate Market and by Hotel Groups for Year 2016",fontsize=25)
g.set_xlabel("Market",fontsize=20)
g.set_ylabel("Rate (in EUR)",fontsize=20)
g.tick_params(labelsize=15)
plt.savefig ('benchmark1.png')
I am OK with my x-axis and y-axis labels font size but the font size of the legend in my plot is small. How to change it?
Use matplotlib function setp according to this example:
import seaborn as sns
import matplotlib.pylab as plt
sns.set_style("whitegrid")
tips = sns.load_dataset("tips")
ax = sns.stripplot(x="sex", y="total_bill", hue="day", data=tips, jitter=True)
plt.setp(ax.get_legend().get_texts(), fontsize='22') # for legend text
plt.setp(ax.get_legend().get_title(), fontsize='32') # for legend title
plt.show()
Another way is to change font_scale of all graph with plotting_context:
http://seaborn.pydata.org/generated/seaborn.plotting_context.html
There is a much easier way to do this today, simply set up your figure and then call
plt.legend(fontsize='x-large', title_fontsize='40')
https://matplotlib.org/api/_as_gen/matplotlib.pyplot.legend.html
Might depend on the version of matplotlib you're using. I'm using 2.2.3 and it has the fontsize parameter but not the title_fontsize.
I am plotting different columns of a year of hourly data from a Pandas dataframe.
I have written the following function to plot:
def plotResults(dfA):
fig, (ax1,ax2) = plt.subplots(2, sharex=True, sharey=False)
ax1.plot(dfA.index, dfA['LP1'], color='blue',alpha=0.7, label='LP1')
ax1.bar(dfA.index, dfA['b'], color='green',alpha=0.1, rwidth=1, label='b')
ax1.bar(dfA.index, dfA['p'].fillna(0), color='red',alpha=0.1, rwidth=1, label='p', bottom=dfA['b'])
ax1.legend(loc='best')
ax2.plot(dfA.index, dfA['Residual'], color='red',alpha=0.7, label='LP1')
ax2.legend(loc='best')
plt.show()
The bars for the bar charts are overlapping for some reason that I do not understand. I have been trying with width = 1.0/(len(dfA.index)) but then the bars get extremely narrow.
How can I set up the bars so they do not overlap and cover one hour (which is the periodicity of dfA)?
There should be gaps between the red bars in the upper graph. They only have values for some hours.
I havent got to any solution about this overlapping bars in the barchart, but I have found a Workaround that solves the problem for me.
Using a stackplot instead of barchart.
def plotResults(dfA):
fig, (ax1,ax2) = plt.subplots(2, sharex=True, sharey=False)
# Upper Chart
# Linechart
ax1.plot(dfA.index, dfA['LP1'], color='blue',alpha=0.7, label='LP1')
# stackplot
ax1.stackplot(dfA.index,dfA['b'],dfA['p'], label=['b', 'p'], colors=['green','red'] ) #stackplot labels do not show in Legend
ax1.plot([], [], color='red', label='p', linewidth=10) #dummy plots only to show labels in the legend
ax1.plot([], [], color='green', label='b', linewidth=10) #dummy plots only to show labels in the legend
ax1.legend(loc='best')
# Lower Chart - Residuals
ax2.plot(dfA.index, dfA['Residual'], color='red',alpha=0.7, label='Residual')
ax2.legend(loc='best')
plt.show()
Using the stackplot is not an answer to the initial issue but it solves the Problem for me.
I'm trying to use Python and Matplotlib to plot a number of different data sets. I'm using twinx to have one data set plotted on the primary axis and another on the secondary axis. I would like to have two separate legends for these data sets.
In my current solution, the data from the secondary axis is being plotted over the top of the legend for the primary axis, while data from the primary axis is not being plotted over the secondary axis legend.
I have generated a simplified version based on the example here: http://matplotlib.org/users/legend_guide.html
Here is what I have so far:
import matplotlib.pyplot as plt
import pylab
fig, ax1 = plt.subplots()
fig.set_size_inches(18/1.5, 10/1.5)
ax2 = ax1.twinx()
ax1.plot([1,2,3], label="Line 1", linestyle='--')
ax2.plot([3,2,1], label="Line 2", linewidth=4)
ax1.legend(loc=2, borderaxespad=1.)
ax2.legend(loc=1, borderaxespad=1.)
pylab.savefig('test.png',bbox_inches='tight', dpi=300, facecolor='w', edgecolor='k')
With the result being the following plot:
As shown in the plot, the data from ax2 is being plotted over the ax1 legend and I would like the legend to be over the top of the data. What am I missing here?
Thanks for the help.
You could replace your legend setting lines with these:
ax1.legend(loc=1, borderaxespad=1.).set_zorder(2)
ax2.legend(loc=2, borderaxespad=1.).set_zorder(2)
And it should do the trick.
Note that locations have changed to correspond to the lines and there is .set_zorder() method applied after the legend is defined.
The higher integer in zorder the 'higher' layer it will be painted on.
The trick is to draw your first legend, remove it, and then redraw it on the second axis with add_artist():
legend_1 = ax1.legend(loc=2, borderaxespad=1.)
legend_1.remove()
ax2.legend(loc=1, borderaxespad=1.)
ax2.add_artist(legend_1)
Tribute to #ImportanceOfBeingErnest :
https://github.com/matplotlib/matplotlib/issues/3706#issuecomment-378407795