Cannot add legend to ggplot line-plot [duplicate] - ggplot2

This question already has answers here:
Add legend to ggplot2 line plot
(4 answers)
Closed 2 years ago.
I am a new R user and I am trying to add a legend to my lines plot. This is the command line that I used to make the plot and the relative plot.
ggplot(crab_tag$daylog, aes(Date))+ geom_line(aes(y=-Max.Depth), color="blue")+ geom_line(aes(y=-Min.Depth),color="violet")+ labs(x="Date",y="Depth(m)")+ theme(legend.position = c(0,1),legend.justification = c(0,1)) +scale_color_manual(values = c("blue","violet"))
Anyone can help me to see my error?
Thanks!

Based on this thread https://community.rstudio.com/t/adding-manual-legend-to-ggplot2/41651/2 I found the following: The issue here is that you have to link the colour to the legend (and also have to call the legend). Here is a solution:
library(tidyverse)`
library(learningr)`
ggplot(crab_tag$daylog, aes(Date)) +
geom_line(aes(y=-Max.Depth, colour = "Max.Depth")) +
geom_line(aes(y=-Min.Depth, colour = "Min.Depth"))+
labs(x="Date",y="Depth(m)", colour = "legend")+
theme(legend.position = c(0,1),legend.justification = c(0,1)) +
scale_color_manual(values = c("Max.Depth"="blue","Min.Depth"="violet"))
You see, the main changes is to call colour within the aes() function and there define the variable name you want to use in the legend, the label of the colour legend in labs, and the named vector for values in scale_colour_manual()

Related

How to save charts without cutting off x-axis labels? [duplicate]

This question already has answers here:
matplotlib savefig - text chopped off
(3 answers)
X and Y label being cut in matplotlib plots
(2 answers)
Closed yesterday.
Could you please help me correctly save chart images?
The saved files has axes x-titles that are cut off? See below:
Current Chart Image
I'm currently using:
ax.figure.set_size_inches(16, 9)
#adjusting the tick marks
plt.xticks(rotation=75)
#saving plot
plt.show()
fig.savefig('figure6.png')
plt.clf()

How to remove ylabel from Seaborn histplot? [duplicate]

This question already has an answer here:
How to remove or hide y-axis ticklabels from a matplotlib / seaborn plot
(1 answer)
Closed 5 months ago.
This is what I have:
fig, ax = plt.subplots(figsize=(4, 3))
sns.histplot(my_data, ax=ax)
ax.set(ylabel='')
But this still seems to allocate the space for the y-axis label, it's only that the label itself is an empty string, which results in wasted space on the left-hand side of the image. I don't want the white space in place of the y-axis label, I really want to remove it.
Both answers suggested in the comments work.
One way to achieve what I want is:
fig, ax = plt.subplots(figsize=(4, 3))
sns.histplot(my_data, ax=ax)
ax.set(ylabel='')
plt.tight_layout(pad=0)
The pad parameter of tight_layout controls the size of the margin around the figure.

Plotting choropleth map with discrete colorbar/legend using Geopandas [duplicate]

This question already has an answer here:
matplotlib geopandas plot chloropleth with set bins for colorscheme
(1 answer)
Closed 3 years ago.
I am trying to make a choropleth map using Geopandas. However I'm having trouble with the colourbar formatting, it seems to be very limited.
Here is the map I have:
But I would like the colorbar(legend?) to be discrete breaks, or a colour key, I'm not really sure what to call it. Something like this:
Is this even possible with Geopandas? I'm finding nothing in their documentation. Maybe something with legend_kwds?
Here is my plotting code
fig, ax = plt.subplots(1, figsize = (20, 12) )
ax.axis('off')
merged.plot(ax = ax, column = '2019-12', color = 'grey', label = 'No Data') #Plots 'No Data' layer
merged.dropna().plot(ax = ax, column = '2019-12', cmap = 'Reds', alpha = 1, legend = True) #Plots data layer
ax.legend()
In an ideal world, I'd also be able to manually set the numbers and limits of the intervals as well.
This answer helped a lot. I was able to use classification_kwds and define my own bins using using the User_Defined scheme argument when calling gpd.plot(). Although I would like more functionality, this is good enough for now.

Setting legend location in matplotlib (while using geopandas)

I have tried several different methods to change my plot's legend's position, but none of them have worked. I would like to set the position for example to upper left or upper right.
I have a GeoDataFrame (data_proj) which has polygons in it. I want to plot only one map with those polygons.
I created my plot like this:
p = data_proj.plot(column = "Level3", linewidth=0.03, legend = True)
I used these to set the title etc. for the legend:
leg = p.get_legend()
leg.set_title("Land cover")
leg.get_frame().set_alpha(0)
How can I change the location of the legend?
On geopandas master (i.e., a change made subsequent to the current 0.3.0 release), a legend_kwds argument was added to the plot method. One can then do the following:
ax = df.plot(column='values', categorical=True, legend=True, legend_kwds={'loc': 2})
In principle setting the legend should work as usual. The loc parameter can be used to define the location of the legend.
p = data_proj.plot(column = "Level3", linewidth=0.03)
leg = p.legend(loc="upper right")
leg.set_title("Land cover")
leg.get_frame().set_alpha(0)

How to autoscale y axis in matplotlib? [duplicate]

This question already has an answer here:
Add margin when plots run against the edge of the graph
(1 answer)
Closed 8 years ago.
I'm currently creating many plots and some look great while other need some adjustment. From below how can I make the hard to see plot line easier to see without having to manually plot them? I plot 50-100 of these at a time then add them to a pdf report. I'd like to add space under the line, for example have ylim min limit set to -0.1, but do it automatically.
This one is hard to see plot line:
This one is easy to see plot line:
Here is my code for plotting:
def plot(chan_data):
'''Uses matplotlib to plot a channel
'''
f, ax = plt.subplots(1, figsize=(8, 2.5))
x = dffinal['time'].keys()
ax.plot(x, dffinal[chan_data].values, linewidth=0.4, color='blue')
ax.xaxis.set_major_formatter(mdates.DateFormatter('%m/%d/%Y - %H:%M'))
ax.xaxis.set_major_locator(mdates.AutoDateLocator(interval_multiples=True))
lgd1 = ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))
f.autofmt_xdate()
ax.set_ylabel(dffinal[chan_data].name)
ax.grid('on')
#I've tried these with no luck
#ax.autoscale(enable=True, axis='y', tight=False)
#ax.set_ymargin(0.5)
#ax.set_autoscaley_on(True)
fname = ".\\plots\\" + chan_data + ".png"
print "Creating: " + fname
plt.savefig(fname, dpi=100, bbox_extra_artist=(lgd1,), bbox_inches='tight')
plt.close()
return fname
You want margins doc
ex
ax.margins(y=.1)
Also see Add margin when plots run against the edge of the graph