Remove the border of a sf polygon when plotted with ggplot2 using geom_sf - ggplot2

I'm working with a shapefile converted from a raster with lots of little holes in it, therefore, the borders create big splodges in the shape when plotted.
I'm currently adding the polygon to the main plot with the below code. Despite setting the alpha value to 1 the colours are different even when both set to "red" which makes no sense to me.
geom_sf(data = filter(db, band == 9), aes(fill = "red"), colour = "red", alpha = 1)
Can I either:
Set the borders to the same colour as the fill?
Or remove the border entirely?
Or set the border colour to none?

Related

Gray matpotlib figure face color turns black when saving the figure as .eps

I am using the following code to get this:
1
However, when saved as .eps, the face color of the figure turns from gray ( what I want) to black. See this:
2
Any reason why?
dim = np.arange(1, 32, 1)
fig, ax = plt.subplots(figsize=(7,9))
heatmap = ax.imshow(h.T, cmap=plt.cm.get_cmap('Blues', 4), clim=[1,144])
cbaxes = fig.add_axes([.8, .35, .04, .3])
cbar = fig.colorbar(heatmap, ticks = [1, 36, 72, 108, 144], label = 'Number of valid records per day', cax = cbaxes)
ax.set_ylabel("Days", fontsize=15)
ax.set_xlabel("Months", fontsize=15)
ax.set_title("Number of valid records per day", fontsize=20)
ax.set_yticks(range(0,31))
ax.set_yticklabels(dim, ha='center', minor=False, fontsize=12)
ax.set_xticks(range(0,13,1))
ax.set_xticklabels(ylabel[7:20], rotation = 45, ha = 'right')
ax.set_facecolor('gray')
cbar.set_label('Number of valid records')
ax.xaxis.set_minor_locator(MultipleLocator(0.5))
ax.yaxis.set_minor_locator(MultipleLocator(0.5))
ax.tick_params(axis='y', which='major', pad=10)
ax.grid(which = 'minor', color = 'w')
fig.show()
plt.savefig("drive/My Drive/fig.eps")
Your problem is probably caused by your 'gray' colour actually being black with transparency (which is the a channel in rgba), i.e. the rgba color (0,0,0,.5), which is black with a 50% transparency. If you ran your code interactively, you should have gotten a message:
"The PostScript backend does not support transparency; partially
transparent artists will be rendered opaque."
.eps (Postscript in the message refers to encapsulated postscript) doesn't support transparency, I imagine under the hood when your figure is being saved as .eps it simply takes the color channels i.e. the rgb values, which is equivalent to setting alpha to 1.
You can either:
Rasterize your figure/axes before saving as .eps using fig.set_rasterized(True)/ax.set_rasterized(True),
Save in a different format which supports transparency (.pdf, .png etc.)
Choose a color/cmap(colormap) which does not include transparency.
To expand #3 for your specific option, if it's the case that missing values aren't plotted and we're seeing the axes facecolor, you can try explicitly specifying an rgb color ax.set_facecolor(.5,.5,.5) instead of ax.set_facecolor('grey').

enlarge contour plot values on the line

I would like to know if there is a way to enlarge the values on the line in a contour plot. Attached after the code is a link to a contour plot like mine, there are values on the line and I would like to enlarge those numerical values on the contour line.
I enlarged the chart so all the axis and title shrunk, but I managed to enlarge the text for the axis and title. Now I am just having issues enlarging the values on the contour lines themselves. Attached below is a portion of the code I wrote.
plt.figure(figsize=(20,20), dpi=400)
contour_graph = plt.contour(R,h_diam,keff_array)
plt.xlabel('Diameter (cm)', size = 20)
plt.ylabel('Height/Diameter', size = 20)
plt.title('Multiplication Factor for Different Deminsions', size = 40)
plt.xticks(size = 20)
plt.yticks(size = 20)
plt.xlim(0,20)
plt.ylim(0,2)
plt.clabel(contour_graph)
plt.grid()
plt.savefig('contourplotratioVdiam.png')
https://www.google.com/imgres?imgurl=https%3A%2F%2Fdoxdrum.files.wordpress.com%2F2010%2F04%2Fvelocity-add.png&imgrefurl=https%3A%2F%2Fdoxdrum.wordpress.com%2F2010%2F04%2F11%2Fcontour-plot-in-sage-and-matplotlib%2F&docid=pyXslh9eixfe-M&tbnid=8AyQEBR6HwVqYM%3A&vet=10ahUKEwjB28HyopbjAhWNQc0KHcAVBgcQMwipASg6MDo..i&w=600&h=370&bih=754&biw=1536&q=contour%20plot%20python&ved=0ahUKEwjB28HyopbjAhWNQc0KHcAVBgcQMwipASg6MDo&iact=mrc&uact=8
The clabel option accepts fontsize as a parameter to control the size of contour labels. From the docs:
clabel(cs, [levels,] **kwargs)
Adds labels to line contours in cs, where cs is a ContourSet object returned by contour().
Parameters:
fontsize : string or float, optional
Size in points or relative size e.g., 'smaller', 'x-large'. See Text.set_size for accepted string values.
So in your case, you can use
plt.clabel(contour_graph, fontsize=24)

Pandas, Bar Chart Annotations

How to properly give Annotations to Pandas Bar Charts?
I'm following Bar Chart Annotations with Pandas and MPL, but somehow I can't make it into my own code -- this is as far as I can go. What's wrong?
I've also found the following code from here:
def autolabel(rects):
# attach some text labels
for rect in rects:
height = rect.get_height()
ax.text(rect.get_x() + rect.get_width()/2., 1.05*height,
'%d' % int(height),
ha='center', va='bottom')
autolabel(rects1)
autolabel(rects2)
But I don't how to apply that to my code either. Please help.
UPDATE:
Thank you #CT Zhu, for the answer. However, in your horizontal bars, you are still placing the text on top of bars, but I need the text show up within or along them, like this from my referenced article,
where s/he says,
"I am very parital to horizontal bar charts, as I really think they are easier to read, however, I understand that a lot of people would rather see this chart implemented in a regular bar chart. So, here is the code to do that; you will notice that a few things have changed in order to create the annotation"*
It appears your autolabel function is expecting a list of patches, sssuming your plot only those bars as its patches, we could do:
df = pd.DataFrame({'score':np.random.randn(6),
'person':[x*3 for x in list('ABCDEF')]})
def autolabel(rects):
x_pos = [rect.get_x() + rect.get_width()/2. for rect in rects]
y_pos = [rect.get_y() + 1.05*rect.get_height() for rect in rects]
#if height constant: hbars, vbars otherwise
if (np.diff([plt.getp(item, 'width') for item in rects])==0).all():
scores = [plt.getp(item, 'height') for item in rects]
else:
scores = [plt.getp(item, 'width') for item in rects]
# attach some text labels
for rect, x, y, s in zip(rects, x_pos, y_pos, scores):
ax.text(x,
y,
'%s'%s,
ha='center', va='bottom')
ax = df.set_index(['person']).plot(kind='barh', figsize=(10,7),
color=['dodgerblue', 'slategray'], fontsize=13)
ax.set_alpha(0.8)
ax.set_title("BarH")#,fontsize=18)
autolabel(ax.patches)
ax = df.set_index(['person']).plot(kind='bar', figsize=(10,7),
color=['dodgerblue', 'slategray'], fontsize=13)
ax.set_alpha(0.8)
ax.set_title("Bar")#,fontsize=18)
autolabel(ax.patches)

small scatter plot markers in matplotlib are always black

I'm trying to use matplotlib to make a scatter plot with very small gray points. Because of the point density, the points need to be small. The problem is that the scatter() function's markers seem to have both a line and a fill. When the markers are small, only the line is visible, not the fill, and the line isn't the right colour (it's always black).
I can get exactly what I want using gnuplot: plot 'nodes' with points pt 0 lc rgb 'gray'
How can I make very small gray points using matplotlib scatterplot()?
scatter([1,2,3], [2,4,5], s=1, facecolor='0.5', lw = 0)
This sets the markersize to 1 (s=1), the facecolor to gray (facecolor='0.5'), and the linewidth to 0 (lw=0).
If the marker has no face (cannot be filled, e.g. '+','x'), then the edgecolor has to be set instead of c, and lw should not be 0:
scatter([1,2,3], [2,4,5], marker='+', edgecolor='r')
The following will no work
scatter([1,2,3], [2,4,5], s=1, marker='+', facecolor='0.5', lw = 0)
because the edge/line will not be displayed, so nothing will be displayed.
The absolute simplest answer to your question is: use the color parameter instead of the c parameter to set the color of the whole marker.
It's easy to see the difference when you compare the results:
from matplotlib import pyplot as plt
plt.scatter([1,2,3], [3,1,2], c='0.8') # marker not all gray
plt.scatter([1,2,3], [3,1,2], color='0.8') # marker all gray
Details:
For your simple use case where you just want to make your whole marker be the same shade of gray color, you really shouldn't have to worry about things like face color vs edge color, and whether your marker is defined as all edges or some edges and some fill. Instead, just use the color parameter and know that your whole marker will be set to the single color that you specify!
In response to zwol's question in comment - my reputation is not high enough to leave comments, so this will have to do: In the event that your colors come from a colormap (i.e., are from a "sequence of values to be mapped") you can use color = as demonstrated in the following:
from matplotlib import pyplot
x = [1,5,8,9,5]
y = [4,2,4,7,9]
numSides = [2,3,1,1,5]
cmap = pyplot.cm.get_cmap("copper_r")
min, max = min(numSides), max(numSides)
for i in range(len(x)):
if numSides[i] >= 2:
cax = pyplot.scatter(x[i], y[i], marker = '+', s = 100, c = numSides[i], cmap = cmap)
cax.set_clim(min, max)
elif numSides[i] == 1:
pyplot.scatter(x[i], y[i], marker = '.', s = 40, color = cmap(numSides[i]))
fig = pyplot.gcf()
fig.set_size_inches(8.4, 6)
fig.savefig('figure_test.png', dpi = 200)
pyplot.show()

Display colored labels in plots with matlab

I'm using the following commands to plot a set of points on a 2d map in matlab
labels = {'label1', ' label2', 'label3',...)
plot(score(:,1),score(:,2), '*')
gname(lables)
Is there a way to choose the color for each label?
Thanks
Return vector of label handles, then you can set color (as well as other text properties) for all or individual labels.
h = gname(lables);
set(h,'color','r') %# set all labels to red
set(h(2),'color','g') %# set 2nd label to green