I have several seaborn bar plot as below, and I would like to add horizontal lines above each set of bars. I know the y coordinates, but how can I automatically get the xmin and ymin range without needing to look at them manually?
sns.countplot(x="class", hue="who", kind="bar", data=titanic)
plt.hlines(y=30, xmin=-0.5, xmax=0.5, color='black', alpha=0.4)
plt.hlines(y=50, xmin=0.6, xmax=1.5, color='black', alpha=0.4)
plt.hlines(y=200, xmin=1.5, xmax=2.5, color='black', alpha=0.4)
Related
How can we add multiple legends in Seaborn jointplot? I`m creating a hexbin jointplot with seaborn, and I want to have two legends, scaling in vertical direction instead of horizontal.
First, how can I have both legends as separate and legend for dates scaling vertically instead of horizontally.
I had a look at these links.
Correctly add a legend to a seaborn jointplot
and
Getting legend in seaborn jointplot
And would it also be possible to have the same background for Hexbins instead of white, which doesn`t match with Seaborn style? And can I also make grid square, instead of rectangular?
sns.set()
g = sns.jointplot(x=x,y=y, kind="hex",color="#4CB391", height=15)
ax = g.ax_joint
sns.regplot(x = new_x,y= new_y, ax=ax, scatter=False)
sns.regplot(x = y_true['fatigue_dem_1'],y= y_true['fatigue_dem_1'], color='red',ax=ax, scatter=False)
g.set_axis_labels('Estimated', 'Predicted', fontsize=20)
g.fig.suptitle("Fatigue Dem 1", fontsize=20)
# adjustment for colorbar
plt.subplots_adjust(left=0.2, right=0.8, top=0.95, bottom=0.2)
# make new ax object for the cbar
cbar_ax = g.fig.add_axes([.85, .2, .05, .6]) # x, y, width, height
plt.colorbar(cax=cbar_ax)
metric_legend, = g.ax_joint.plot([], [], linestyle="", alpha=0.5)
data_legend, = g.ax_joint.plot([], [], linestyle="", alpha=0.5)
g.ax_joint.legend([metric_legend],['rrmse={:f}, r2_score={:f}'.format(rrmse,r2)], fontsize=14)
g.ax_joint.legend([data_legend],['Start Date: {0}, End Date: {1}, purpose: {2}'.format(start_date, end_date, 'Test')], fontsize=14)
I'm a beginner in python. I have to plot two graphs in the same plot. One of my graphs is velocity, which ranges between (-1,1), and the other one is groundwater, which ranges between (10,12). When I use the following code, the graphs become very small.
ax1 = plt.subplot(111)
ax2 = ax1.twinx()
df=pd.read_excel ('final-all-filters-0.6.xlsx')
df['Date']=pd.to_datetime(df['Date'])
date = df['Date']
gwl = df['gwl']
v =df['v']
plt.plot(date,gwl, color='deepskyblue',linewidth=2)
plt.plot(date,v, color='black',linewidth=2)
ax1.grid(axis='y')
ax1.xaxis.set_major_locator(matplotlib.dates.YearLocator())
ax1.xaxis.set_minor_locator(matplotlib.dates.MonthLocator((1,3,5,7,9,11)))
ax1.xaxis.set_major_formatter(matplotlib.dates.DateFormatter("\n%Y"))
ax1.xaxis.set_minor_formatter(matplotlib.dates.DateFormatter("%b"))
ax1.grid(which='minor', alpha=0.3, linestyle='--')
ax1.grid(which='major', alpha=2)
for spine in ax1.spines.values():
spine.set_edgecolor('gray')
ax1.tick_params(axis='x', which='both', colors='gray')
ax1.tick_params(axis='y', colors='gray')
ax1.set_ylabel('v', color='g')
ax2.set_ylabel('GWL', color='b')
plt.show()
But when I add the ax1.set_ylim(-1, 1)and ax2.set_ylim(10, 12) to my code, one of the graph was disappered!
I think it does plot the black graph, but it's out of range. You can check that by adding 11 or something to the black plot value.
Maybe you can try using ax2.set_yticks(np.arange(-1, 1, 0.5)) instead of set_ylim and/or using ax2.autoscale(enable=True, axis=y)
I'm plotting a simple scatter plot:
It represents my data correctly, however there is many datapoints with coordinates (1.00,1.00) and in the plot, they appear under a single marker (top right corner). I'd like to have a functionality that changes the size of every marker according to the number of points it is representing. Will appreciate any help. Here's my code:
def saveScatter(figureTitle, xFeature, yFeature, xTitle, yTitle):
''' save a scatter plot of xFeatures vs yFeatures '''
fig = plt.figure(figsize=(8, 6), dpi=300)
ax = fig.add_subplot(111)
ax.scatter(dfModuleCPositives[names[xFeature]][:], dfModuleCPositives[names[yFeature]][:], c='r', marker='x', alpha=1, label='Module C Positives')
ax.scatter(dfModuleCNegatives[names[xFeature]][:], dfModuleCNegatives[names[yFeature]][:], c='g', alpha=0.5, label='Module C Negatives')
ax.scatter(dfModuleDPositives[names[xFeature]][:], dfModuleDPositives[names[yFeature]][:], c='k', marker='x', alpha=1, label='Module D Positives')
ax.scatter(dfModuleDNegatives[names[xFeature]][:], dfModuleDNegatives[names[yFeature]][:], c='b', alpha=0.5, label='Module D Negatives')
ax.set_xlabel(xTitle, fontsize=10)
ax.set_ylabel(yTitle, fontsize=10)
ax.set_title(figureTitle)
ax.grid(True)
ax.legend(loc="lower right")
fig.tight_layout()
plt.show()
return ax
I have created a bubble plot using seaborn, and used matplotlib to draw the legend to the right of my seaborn plots. I specified the sizing of the bubbles in my seaborn code using sizes=(1,900) but the scaling on my matplotlib legend does not reflect what the plots show. The legend reads from 0 to 45 but the actual data in my plots range from 0 to 900
fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(11,4))
sns.scatterplot(y="Min", x="Max",
size="Count", sizes=(1,900), alpha=0.5,
color='r', data=code1, ax=ax1, legend=False)
sns.scatterplot(y="Min", x="Max", alpha=0.5,
color='b', size="Count", sizes=(1,900),
data=code2, ax=ax2, legend=False)
sns.scatterplot(y="Min", x="Max", alpha=0.5,
color='g', size="Count", sizes=(1,900),
data=code3, ax=ax3)
ax3.legend(loc='upper right', bbox_to_anchor=(1.7,1), labelspacing=2,
fontsize=14, frameon=False, markerscale=1)
Here is my plot
I was unable to figure out how seaborn structures the legend output for ingestion by matplotlib. I did learn that my data (code1, code2, and code3) had different min and max values which should have been specified under seaborn's sizes argument. For code1, sizes=(1,900); for code2, sizes=(1,300); for code3, sizes=(1,45). Because I was using matplotlib to draw the legend to the right of code3's plot, the scaling was specific to the rightmost plot rather than for all 3 plots. In the end, I ended up using matplotlib's legend_elements as follows:
fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(12,4))
scatter = ax1.scatter(y=code1["Min"], x=code1["Max"],
s=code1["Count"],
color='r', alpha=0.5)
ax2.scatter(y=code2["Min"], x=code2["Max"],
color='b', s=code2["Count"], alpha=0.5)
ax3.scatter(y=code3["Min"], x=code3["Max"],
color='g', s=code3["Count"], alpha=0.5)
kw = dict(prop="sizes", num=[10,100,500,900])
legend = ax3.legend(*scatter.legend_elements(**kw), title="Count", fontsize=12,
loc='upper right', bbox_to_anchor=(1.5,1), labelspacing=2,
frameon=False)
I have a seaborn Facetgrid, stripplot
m=sns.FacetGrid(group, col='myGroupCol' , size=15, aspect=0.9, sharex=False, sharey=True)
m.map(sns.stripplot,'myX','myY',hue='myColorBy',data=pandas.groupby(), order=order_list, jitter=0.4, hue_order=\
['T','C','TT','TC','CT','CC'],palette="Set1", split=True, size=15, linewidth=2, edgecolor="gray").set(ylim=(-2,6))
for ax,title in zip(m.axes.flat, sorted(titles.iterkeys())):
ax.tick_params(axis='x', which='major', pad=15)
ax.grid(True)
ax.legend(bbox_to_anchor=(1.05, 1),loc=2)
I have tried to changes the spacing between the sticks using tick params but I don't see any change in width.
Any idea what I am doing wrong?
Well just adjusted the aspect ratio and jitter appropriately and got the desired plot.