I was trying to plot a vertical line with markers on it using ax.axvline but the markers only show up on the bottom and top of the figure. I have played around with the markevery kwarg but it does not seem to have any effect when I change it even though it works for a normal line plot. Does anyone know if this is because no discrete values are specified along the axis or am I just doing something wrong?
I realize that I can plot a vertical line on my own and specify the markers, but I figure given the purpose of axvline I should use it.
Here is an example code of what I am talking about:
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(-10,10)
y = x**2-15.
fig = plt.figure(figsize=(4,4))
ax = plt.subplot(111)
ax.plot(y,x) #Test curve
ax.plot(2+np.zeros(len(x)),x,marker='X',markevery=1) #another way to plot what I want.
ax.axvline(0,c='r',marker='X',markevery=1) #markerevery doesn't seem to work
plt.show()
As mentioned by ImportanceofBeingErnest, the markereverykwarg does not apply for axvline or axhline because there are technically only 2 points used to draw the line at the boundaries.
Related
This question already has an answer here:
Drawing a colorbar aside a line plot, using Matplotlib
(1 answer)
Closed 1 year ago.
Let's say I have one figure with a certain number of plots, which resembles like this one:
where the colors of the single plots are decided automatically by matplotlib. The code to obtain this is very simple:
for i in range(len(some_list)):
x, y = some_function(dataset, some_list[i])
plt.plot(x, y)
Now suppose that all these lines depend on a third variable z. I would like to include this information plotting the given lines with a color that gives information about the magnitude of z, possibly using a colormap and a colorbar on the right side of the figure. What would you suggest me to do? I exclude to use a legend since in my figures I have many more lines that the ones I am showing. All information I can find is about how to draw one single line with different colors, but this is not what I am looking for. I thank you in advance!
Here it is some code that, in my opinion, you can easily adapt to your problem
import numpy as np
import matplotlib.pyplot as plt
from random import randint
# generate some data
N, vmin, vmax = 12, 0, 20
rd = lambda: randint(vmin, vmax)
segments_z = [((rd(),rd()),(rd(),rd()),rd()) for _ in range(N)]
# prepare for the colorization of the lines,
# first the normalization function and the colomap we want to use
norm = plt.Normalize(vmin, vmax)
cm = plt.cm.rainbow
# most important, plt.plot doesn't prepare the ScalarMappable
# that's required to draw the colorbar, so we'll do it instead
sm = plt.cm.ScalarMappable(cmap=cm, norm=norm)
# plot the segments, the segment color depends on z
for p1, p2, z in segments_z:
x, y = zip(p1,p2)
plt.plot(x, y, color=cm(norm(z)))
# draw the colorbar, note that we pass explicitly the ScalarMappable
plt.colorbar(sm)
# I'm done, I'll show the results,
# you probably want to add labels to the axes and the colorbar.
plt.show()
I am new to python and I am trying to plot x and y (both have a large number of data) but when I use a plt.plot there is not plot visible on the output.
The code I have been using is
for i in range(len(a)):
plt.plot(a[i],b[i])
plt.figure()
plt.show()
when I tried a scatter plot
for i in range(len(a)):
plt.scatter(a[i],b[i])
plt.figure()
plt.show()
I am not able to understand the reason for missing the line plot and even when I try seaborn it showing me an error ValueError: If using all scalar values, you must pass an index
import numpy as np
import matplotlib.pyplot as plt
a = np.linspace(0,5,100)
b = np.linspace(0,10,100)
plt.plot(a,b)
plt.show()
I think this answers your question. I have taken sample values of a and b. The matplotlib line plots are not required to run in loops
A line is created between two points. If you are plotting single values, a line can't be constructed.
Well, you might say "but I am plotting many points," which already contains part of the answer (points). Actually, matplotlib.plot() plots line-objects. So every time, you call plot, it creates a new one (no matter if you are calling it on the same or on a new axis). The reason why you don't get lines is that only single points are plotted. The reason why you're not even seeing the these points is that plot() does not indicate the points with markers per default. If you add marker='o' to plot(), you will end up with the same figure as with scatter.
A scatter-plot on the other hand is an unordered collection of points. There characteristic is that there are no lines between these points because they are usually not a sequence. Nonetheless, because there are no lines between them, you can plot them all at once. Per default, they have all the same color but you can even specify a color vector so that you can encode a third information in it.
import matplotlib.pyplot as plt
import numpy as np
# create random data
a = np.random.rand(10)
b = np.random.rand(10)
# open figure + axes
fig,axs = plt.subplots(1,2)
# standard scatter-plot
axs[0].scatter(a,b)
axs[0].set_title("scatter plot")
# standard line-plot
axs[1].plot(a,b)
axs[1].set_title("line plot")
I'm plotting a simple lineplot with seaborn and I'd like to add a marker in two specific points of the lineplot.
I checked the documentation, and I know that matplotlib has some markers support (https://matplotlib.org/3.1.0/api/markers_api.html), but I couldn't find a solution for my problem.
I have something like this:
sns.lineplot(x="time", y="cost",
data=df_time)
I'd want to specify the plot to have a marker at both the rows n1 and n2. Is that possible?
The show a marker of the first and second point of a line plot use the markevery argument.
import matplotlib.pyplot as plt
x = [1,3,4,6,7,9]
y = [3,2,3,1,3,2]
plt.plot(x,y, marker="s", ms=12, markevery=[0,1])
plt.show()
I tried to get the legend right for the dashed line so I played with the rcParams a little bit, but it for some reasons wouldn't work on my computer.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
matplotlib.rcParams['legend.numpoints'] = 5
matplotlib.rcParams['legend.scatterpoints'] = 5
fig, axs = plt.subplots()
axs.plot(range(10), '--k', label="line")
axs.plot(range(10), range(10)[::-1], ':k', label="scatter")
axs.legend(loc=9)
plt.show()
And the resultant figure is:
And as can be seen, the numpoints for the dashed line is not enough. Would anyone please help?
Thanks!
If you make a plot with markers, matplotlib.rcParams['legend.numpoints'] adjust the number of points drawn on the legend lines.
If you substitute your plot by these:
axs.plot(range(10), '--k', label="line", marker='d')
axs.plot(range(10), range(10)[::-1], ':k', label="scatter", marker='o')
you get this image:
I don't know what does matplotlib.rcParams['legend.scatterpoints'] do, but I guess regulates the number of points in the legend of scatter plots.
If you want to change the length of the lines in the legend give a try with matplotlib.rcParams['legend.handlelength'] and/or matplotlib.rcParams['legend.handleheight']. More info about rc file can be found here
As suggested by #tcaswell, you don't have to set rc parameters. All the legend.* parameters are available as keywords for the legend function. See matplotlib.pyplot.legend documentation
I'm using the matplotlib library in python to generate publication-quality xy scatter plots. I ran into a problem regarding the markers in the legend. I'm plotting 2 different xy-scatter series; one is a set of xy points that forms a curve, and the other is a single xy point.
I would like the legend to show 3 markers for the "curve", and 1 marker for the single point. The only way I know how to change the number of legend markers is using the "scatterpoints" argument when declaring the legend. However, this argument sets the number of markers for all series in the legend, and I'm not sure how to change each legend entry individually.
Sadly I can't post pictures as a new user, but hopefully this description is sufficient. Is there a way to set scatterpoints values individually for each legend entry using matplotlib?
EDIT: Here are links showing images with different values for scatterpoints.
scatterpoints = 3: http://imgur.com/8ONAT
scatterpoints = 1: http://imgur.com/TFcYV
Hopefully this makes the issue a bit more clear.
you can get the line in legend, and change it yourself:
import numpy as np
import pylab as pl
x = np.linspace(0, 2*np.pi, 100)
pl.plot(x, np.sin(x), "-x", label=u"sin")
pl.plot(x, np.random.standard_normal(len(x)), 'o', label=u"rand")
leg = pl.legend(numpoints=3)
l = leg.legendHandles[1]
l._legmarker.set_xdata(l._legmarker.get_xdata()[1:2])
l._legmarker.set_ydata(l._legmarker.get_ydata()[1:2])
##or
#l._legmarker.set_markevery(3)
pl.show()
Legend.legendHandles is a list of all the lines in legend, and the _legmarker attribute of the line is the marks.
You can call set_markevery(3) or set_xdata() & set_ydata() to change the number of marks.