classes=['1','-1']
colors = {1:'red',-1:'green'}
fig, axs = plt.subplots(1,1,figsize=(10,10))
axs.set_xlabel('X1')#Features
axs.set_ylabel('X2')#Features
axs.set_title('Scatter plot of Data Target VS Features')
plt.scatter(X[X.columns[0]],X[X.columns[1]],c=Y.map(colors),label=classes,cmap=Y.map(colors))
axs.grid(True)
legend1=axs.legend(['-1','1'],loc="lower left", title="CLass",frameon=False)
axs.add_artist(legend1)
plt.show()
Here above is my code to simply scatter a dataset and it was working well until it comes to Legend.
I want to set each class its related tag as Legend but I get the below result and it does not help with the red data:
As we can see we only have green data legend and not the red one:
I don't want to use for_loop or anything strange.
I've seen similar questions but can't figure out how to fix them.
Why not just
scatter_plot = plt.scatter(
X[X.columns[0]],
X[X.columns[1]],
c=Y.map(colors),
label=classes,
cmap=Y.map(colors)
)
plt.legend(
handles=scatter_plot.legend_elements()[0],
labels=classes,
loc="lower left",
title="Class"
)
Related
I try to figure out how to create scatter plot in matplotlib with two different y-axis values.
Now i have one and need to add second with index column values on y.
points1 = plt.scatter(r3_load["TimeUTC"], r3_load["r3_load_MW"],
c=r3_load["r3_load_MW"], s=50, cmap="rainbow", alpha=1) #set style options
plt.rcParams['figure.figsize'] = [20,10]
#plt.colorbar(points)
plt.title("timeUTC vs Load")
#plt.xlim(0, 400)
#plt.ylim(0, 300)
plt.xlabel('timeUTC')
plt.ylabel('Load_MW')
cbar = plt.colorbar(points1)
cbar.set_label('Load')
Result i expect is like this:
So second scatter set should be for TimeUTC vs index. Colors are not the subject;) also in excel y-axes are different sites, but doesnt matter.
Appriciate your help! Thanks, Paulina
Continuing after the suggestions in the comments.
There are two ways of using matplotlib.
Via the matplotlib.pyplot interface, like you were doing in your original code snippet with .plt
The object-oriented way. This is the suggested way to use matplotlib, especially when you need more customisation like in your case. In your code, ax1 is an Axes instance.
From an Axes instance, you can plot your data using the Axes.plot and Axes.scatter methods, very similar to what you did through the pyplot interface. This means, you can write a Axes.scatter call instead of .plot and use the same parameters as in your original code:
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.scatter(r3_load["TimeUTC"], r3_load["r3_load_MW"],
c=r3_load["r3_load_MW"], s=50, cmap="rainbow", alpha=1)
ax2.plot(r3_dda249["TimeUTC"], r3_dda249.index, c='b', linestyle='-')
ax1.set_xlabel('TimeUTC')
ax1.set_ylabel('r3_load_MW', color='g')
ax2.set_ylabel('index', color='b')
plt.show()
I am drawing these 2 QQ plots with scipy and then Matplolib. I can neither plot a legend (please see error, "no handles with labels found") nor make changes to the style or colors of line/plo. I suspect because I cannot grab the object.
Can you help fix this?
adding legend
change plot color let's say to purple
change line style to "- -"
Thank you!
fig = plt.figure()
fig.set_size_inches(10, 5)
ax1 =plt.subplot(121)
ax2=plt.subplot(122)
stats.probplot(arr1, dist=stats.norm, plot=ax1)
ax1.set_title("Probability Plot",fontsize=14)
ax1.set_ylabel("Sample Quantiles",fontsize=12)
ax1.set_xlabel("Theoretical Quantiles",fontsize=12)
stats.probplot(arr2, dist=stats.norm, plot=ax2)
ax2.set_title("Probability Plot",fontsize=14)
ax2.set_ylabel("Sample Quantiles",fontsize=12)
ax2.set_xlabel("Theoretical Quantiles",fontsize=12)
ax2.legend()
plt.show()
For the legend you can pass the string into ax2.legend()
ie. ax2.legend('string')
Regarding colors and style you can try ax.get_lines(), checkout the doc for lineobject and another post here
To have a custom marker, I made two scatter plots with same data points but different markers. Thus by plotting one marker on top of the other I get the look of a new custom marker. Now I want to use it in legend. Is there a way I can use two markers one on top of the other in legend and show them as a single marker.
Edit:
The question is not regarding how to share the same label for two different markers, but how to plot one marker on top of other in the legend
Using a tuple of markers answers the question;
from numpy.random import randn
m=np.random.uniform(size=10)
x=np.arange(0,10,1)
y=x**2
fig, ax = plt.subplots(1,1)
blue_dot = ax.scatter(x[:5],y[:5], s=m*100, color='b')
red_dot = ax.scatter(x[5:],y[5:], s=200*m, color='r')
black_cross = ax.scatter(x[5:],y[5:], s=400*m, marker='+', color='k')
lgnd = ax.legend([blue_dot, (red_dot, black_cross)], ["Blue Circle", "Red Circle and Black Cross"])
Now I want to change the size of the markers in the legend so that all the markers of equal size. For that, I have tried adding this to above code.
lgnd.legendHandles[0]._sizes = [200]
lgnd.legendHandles[1]._sizes = [200] # this is affecting the size of red_dot only
How do I change the size of black_cross as well in the legend?
I am trying to change location of plot legend. Below what I've got for now.
var_list=powiaty_cols[powiaty_cols.str.contains("apart_bel_40")]
for var in var_list:
fig = plt.figure(figsize=(25, 25))
ax = plt.gca()
powiaty.plot(column=var,cmap='Reds', categorical=True,
legend=True, ax=ax,edgecolor='black')
ax.legend(loc='best')
This code is plotting figure but without legend. I've received errors as follows:
No handles with labels found to put in legend.
No handles with labels found to put in legend.
No handles with labels found to put in legend.
No handles with labels found to put in legend.
But without part 'ax.legend(loc='best')' I can get my plot but legend is in upper left corner. Plotted column is filled with integer from 1 to 5. Similar issue is when I'm trying to change size of legend.
Could maybe somebody help in this?
I don't know what powiaty is, but my guess is that you need to get the Axes object back so you can continue modifying it. Try:
ax = powiaty.plot(column=var, cmap='Reds', categorical=True,
legend=True, ax=ax, edgecolor='black'
)
For me worked:
leg = ax.get_legend()
leg.set_bbox_to_anchor((0., 0.1, 0.2, 0.2))
I have the following plot:
dfA.plot.bar(stacked=True, color=[colorDict.get(x, '#333333') for x in
dfA.columns],figsize=(10,8))
plt.legend(loc='upper right', bbox_to_anchor=(1.4, 1))
Which displays this:
I want to remove all of the borders of the chart and legend i.e. the box around the chart (leaving the axis numbers like 2015 and 6000 etc)
All of the examples I find refer to spines and 'ax', however I have not built my chart using fig = plt.figure() etc.
Anyone know how to do it?
You can remove the border of the legend by using the argument frameon=False in the call to plt.legend().
If you only have one figure and axes active, then you can use plt.gca() to get the current axes. Alternatively df.plot.bar returns an axes object (which I would suggest using because plt.gca() might get confusing when working with multiple figures). Therefore you can set the visibility of the spines to False:
ax = dfA.plot.bar(stacked=True, color=[colorDict.get(x, '#333333') for x in
dfA.columns],figsize=(10,8))
plt.legend(loc='upper right', bbox_to_anchor=(1.4, 1), frameon=False)
for spine in ax.spines:
ax.spines[spine].set_visible(False)
# Color of the spines can also be set to none, suggested in the comments by ScoutEU
# ax.spines[spine].set_color("None")