Scatter plot with two data sets - python

The following code plots two lines. Instead I need dots without lines:
plt.plot(y1, marker='o', color='b')
plt.plot(y2, marker='o', color='r')
plt.show()
What should I change to get proper result?

You could use plt.scatter to get a scatter plot.
import matplotlib.pylot as plt
plt.scatter(x, y1)
plt.scatter(x, y2)
plt.show()
You would set x to be a list containing the corresponding x axis values for your series. For instance, if your data start from x=0 and go up by one, you could use x = range(len(y1)) as your x axis series.

I would do the following:
plt.plot(y1, marker='o', linestyle=None, color='b')
plt.plot(y2, marker='o', linestyle=None, color='r')
plt.show()
EDIT: the linestyle=None raises an Error. You can use linestyle='' or directly:
plt.plot(y1,'bo')
plt.plot(y2,'ro')
plt.show()
should work.

Related

Scatter plot with infinitesimal point size in Python

Is it possible to do scatter plot in python, having points have minimal size of 1 pixel at given scale? I.e. points should not scale as I scale the plot and have size of 1 pixel always.
In pyplot
plt.scatter(d3_transformed[:,0], d3_transformed[:,1], s=1)
I still get fat point like this
You can change the marker to a point by setting marker='.', and then further reduce its size by removing the outline using linewidths=0. Note that markeredgewidth does not work with scatter.
Consider this example. As you can see, the last line of points plotted (marker='.', s=1, linewidths=0) gives the smallest markers:
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots(1)
x = np.linspace(0, 10, 100)
ax.scatter(x, np.ones_like(x)+0, marker='o', s=1, color='k')
ax.scatter(x, np.ones_like(x)+1, marker='o', s=1, color='k', linewidths=0)
ax.scatter(x, np.ones_like(x)+2, marker='.', s=1, color='k')
ax.scatter(x, np.ones_like(x)+3, marker='.', s=1, color='k', linewidths=0)
plt.show()
In scatterplot, the points have marker which is a symbol, like circle, and this symbol has also a border. I think the border is on by default. Try to turn off the bored, like set its width to 0.
http://matplotlib.org/api/lines_api.html#matplotlib.lines.Line2D.set_markeredgewidth

Change ticks of y-axis in python

I want to change y axis ticks in python. I am using the code
import pylab as plt
y1 = [0,1,2,...10]
y2 = [90,40,65,12,....]
labels = [0.30,0.29,0.28,....]
plt.plot(y1)
plt.plot(y2,'r')
plt.yticks(y1, labels)
plt.yticks(y2, labels)
plt.show()
But all the y axis label appear at one place on top of one another
Borrowing heavily from this example, the code below demonstrates one possible way to have two plots on one figure.
import pylab as plt
fig, ax1 = plt.subplots()
y1 = [0,1,2,3,4,5,6,7,8,9,10]
labels = [0.30,0.29,0.28,0.27,0.26,0.25,0.24,0.23,0.22,0.21,0.20]
ax1.plot(labels, y1, 'b-')
ax1.set_xlabel('labels')
# Make the y-axis label, ticks and tick labels match the line color.
ax1.set_ylabel('y1', color='b', rotation="horizontal")
ax1.tick_params('y', colors='b')
ax2 = ax1.twinx()
y2 = [90,40,65,12,23,43,54,13,42,53,63]
ax2.plot(labels, y2, 'r-')
ax2.set_ylabel('y2', color='r', rotation="horizontal")
ax2.tick_params('y', colors='r')
fig.tight_layout()
plt.show()

figure/subplot confusion with regard to x/y limits

I am trying to set the x and y limits on a subplot but am having difficultly. I suspect that the difficultly stems from my fundamental lack of understanding of how figures and subplots work. I have read these two questions:
question 1
question 2
I tried to use that approach, but neither had any effect on the x and y limits. Here's my code:
fig = plt.figure(figsize=(9,6))
ax = plt.subplot(111)
ax.hist(sub_dict['b'], bins=30, color='r', alpha=0.3)
ax.set_ylim=([0,200])
ax.set_xlim=([0,100])
plt.xlabel('x')
plt.ylabel('y')
plt.title('title')
plt.show()
I am confused as whether to apply commands to fig or ax? For instance .xlabel and .title don't seem to be available for ax. Thanks
Why don't you do:
Ax = fig.add_subplot(111)
import matplotlib.pyplot as plt
import numpy as np
mu, sigma = 100, 15
x = mu + sigma*np.random.randn(100)
fig = plt.figure(figsize=(9,6))
ax = fig.add_subplot(111)
ax.hist(x, bins=30, color='r', alpha=0.3)
ax.set_ylim=(0, 200)
ax.set_xlim=(0, 100)
plt.xlabel('x')
plt.ylabel('y')
plt.title('title')
plt.show()
I've run your code on some sample code, and I'm attaching the screenshot. I'm not sure this is the desired result but this is what I got.
For a multiplot, where you have subplots in a single figure, you can have several xlabel and one title
fig.title("foobar")
ax.set_xlabel("x")
This is explained in great detail here on the Matplotlib website.
You in your case, use a subplot for just a single plot. This is possible, just doesn't make a lot of sense. Plots like the one below are supposed to be created with the subplot feature:
To answer your question: you can set the x- and y-limits on a per-subplot and per-axis basis by simply addressing the respective subplot directly (ax for subplot 1) and them calling the set_xlabel member function to set the label on the x-axis.
EDIT
For your updated question:
Use this code as inspiration, I had to generate some data on my own so no guarantees:
import matplotlib.pyplot as plt
plt.hist(sub_dict['b'], bins=30, color='r', alpha=0.3)
plt.ylim(0,200)
plt.xlim(0,100)
plt.xlabel('x')
plt.ylabel('y')
plt.title('title')
plt.show()
Bit more googling and I got the following that has worked:
sub_dict = subset(data_dict, 'b', 'a', greater_than, 10)
fig = plt.figure(figsize=(9,6))
ax = fig.add_subplot(111)
ax.hist(sub_dict['b'], bins=30, color='r', alpha=0.3)
plt.ylim(0,250)
plt.xlim(0,100)
plt.xlabel('x')
plt.ylabel('y')
plt.title('title')
plt.show()

Saving plot from ipython notebook produces a cut image

I am plotting a plot with 2 ylabels using ipython notebook and the image looks good when visualized inside the notebook.
Here is how I do it:
import matplotlib.pyplot as plt
fig, ax1 = plt.subplots()
plt.title('TITLE')
plt.xlabel('X')
plt.plot(x, y1, '-', color='blue', label='SNR')
ax1.set_ylabel('y1', color='blue')
for tl in ax1.get_yticklabels():
tl.set_color('blue')
ax2 = ax1.twinx()
plt.plot(x, y2, '--', color='red', label='Ngal')
ax2.set_ylabel('y2', color='red')
for tl in ax2.get_yticklabels():
tl.set_color('red')
The problem is that when I try to save it with the command
plt.savefig('output.png', dpi=300)
since the output will be an image which is cut on the right side: basically I don't see the right ylabel if the right numbers are large.
By default, matplotlib leaves very little room for x and y axis labels and tick labels, therefore you need to adjust the figure to include more padding. Fortunately this could not be easier to do. Before you call savefig, you can call call
fig.tight_layout()
plt.savefig('output.png', dpi=300)
Alternatively, you can pass bbox_inches='tight' to savefig which will also adjust the figure to include all of the x and y labels
plt.savefig('output.png', dpi=300, bbox_inches='tight')

matplotlib plotting the wrong indices

I'm trying to plot both a line plot and scatter plot on the same figure. The scatter plot looks great, but the line is plotted at the incorrect indices. That is, the scatter plot data is along the correct indices, [0,4621], but the line plot is "bunched up" into indices [3750,4621].
plt.figure()
plt.plot(ii, values,
color='k', alpha=0.2)
plt.scatter(ii, scores,
color='g', s=20, alpha=0.3, marker="o")
plt.scatter(jj, scores[scores >= threshold],
color='r', s=20, alpha=0.7, marker="o")
plt.scatter(kk, labels[labels==1],
color='k', s=20, alpha=1.0, marker="+")
plt.axis([0, len(labels), 0, 1.1])
plt.title(relativePath)
plt.show()
The issue is the axes setting plt.axis([0, len(labels), 0, 1.1]) because values does not fit in the y-axis bounds. So normalizing the values list keeps it within the specified bounds [0,1.1]. This is done with norm_values = [float(v)/max(values) for v in values].

Categories

Resources