I am familiar with numpy.transpose command that it is used to swap axes. But I am not familiar with mirror images that what they are and how numpy.transpose command is used to generate mirror image. The following link says that when we swap last two axis we get mirror images. So what is meant by mirror images here. I will be really thankful if someone please explain this with some picture
`a= np.arange(2*2*4).reshape(2,2,4)
b= np.transpose(a,(1,0,2))`
please look https://imgur.com/gallery/v6z7ah0
https://www.reddit.com/r/learnpython/comments/734lcl/complicated_numpy_transpose_question/?st=jij0av7a&sh=754dfd45
In [54]: a= np.arange(2*3*4).reshape(3,2,4)
# | | |
# axes 0 1 2
# new shape by moving the axes
In [54]: b= np.transpose(a,(1,0,2))
In [55]: a.shape
Out[55]: (3, 2, 4)
# first two axes are swapped
In [56]: b.shape
Out[56]: (2, 3, 4)
By default, np.transpose() reverses the shape. But, when passing an argument to np.transpose() the array is reshaped to the requested shape if possible.
Explanation:
In the above example, np.transpose(a, (1, 0, 2)) means that in the returned array b, the zeroth and first axes would be swapped.
Specifically, the tuple that's passed to np.transpose() is the order in which we want our resultant array to have the shape.
Plotting the image before (left) and after transposing (right):
Related
I am trying to create a corner plot for an upcoming paper, but I'm running into difficulty. I am creating an N x N array of subplots (currently, N = 6) and then deleting a bit over half of them. The issue is that the figure doesn't seem to resize itself after I delete the extraneous subplots, so when I later add a legend using a dummy subplot, it exists in the area where a full row and column of deleted subplots were, thus enlarging the figure. I've been working on this for several hours now and haven't found a solution. Here is the MWE:
import matplotlib.pyplot as plt
%matplotlib notebook
n_char = 8
# Set up the main figure.
fig, ax = plt.subplots(n_char, n_char, figsize=(n_char, n_char))
# Get rid of the axis labels unless it's on the left-most column or bottom-most row.
for i in range(0, n_char):
# For each row, loop over each column.
for j in range(0, n_char):
# If the plot isn't in the bottom-most row, get rid of the x-axis tick labels.
if i != n_char - 1:
ax[i, j].set_xticklabels([])
# If the plot isn't in the left-most column, get rid of the y-axis tick labels.
if j != 0:
ax[i, j].set_yticklabels([])
# Remove the plots that are repetitive or boring (plotting against the same characteristic).
for i in range(0, n_char):
# For each row, loop over each column.
for j in range(0, n_char):
# Delete the offending axes.
if j >= i:
ax[i, j].remove()
# Set the spacing between the plots to a much smaller value.
fig.subplots_adjust(hspace=0.00, wspace=0.00)
# Create a big plot for the legend. Have the frame hidden.
fig.add_subplot(111, frameon=False, xticks=[], yticks=[], xticklabels=[], yticklabels=[])
# Create some dummy data to serve as the source of the legend.
plt.scatter([10], [10], color="k", s=5, zorder=2, label="Targets")
# Set the x-axis limits such that the dummy data point is invisible.
fig.gca().set_xlim(-1, 1)
# Add the legend to the plot. Have it located in the upper right.
plt.legend(scatterpoints=1, loc="upper right", fontsize=5)
# Save the final plot.
fig.savefig("./../Code Output/Other Plots/Corner_Plot_Test.png", bbox_inches="tight", dpi=500)
I have looked at many different questions here on Stack Overflow. The two most promising candidates was this one, but I found the solution wasn't quite workable due to the large number of plots (and, to be frank, I didn't fully understand the solution). I thought that the first answer in this one might also work, as I thought it was a sizing issue (i.e. the figure wasn't resizing, so creating a new subplot was creating one the size of the original figure), but all it did was resize the entire figure, so that didn't work either.
To help, I will also include an image. I took the output of the code above and edited it to show what I want:
I should add that if I don't add a subplot, the output is as I expected (i.e. it's the proper size), so the issue comes in when adding the subplot, i.e. the line fig.add_subplot(111, frameon=False, xticks=[], yticks=[], xticklabels=[], yticklabels=[]).
The use of GridSpec may help.
GridSpec is used to specify array of axes to plot. You can set widths for columns and heights for rows as ratios in the option. The unneeded row should have very small height ratio, while unneeded column very small width ratio.
Here is the runnable code and output plot:-
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
#import numpy as np
fig = plt.figure(figsize=(8, 8))
nn = 6
# will create gridspec of 6 rows, 6 columns
# 1st row will occupy v small heights
# last column will occupy v small widths
sm = 0.01 # the v small width/height
wh = (1.-sm)/(nn-1.) # useful width/height
gs = gridspec.GridSpec(nn, nn, width_ratios=[*[wh]*(nn-1), sm], \
height_ratios= [sm, *[wh]*(nn-1)])
cols, rows = nn, nn
ax = [[0 for i in range(cols)] for j in range(rows)]
for ea in range(nn):
for eb in range(nn):
ax[ea][eb] = fig.add_subplot(gs[ea, eb])
ax[ea][eb].set_xticklabels([])
ax[ea][eb].set_yticklabels([])
if eb>=ea:
ax[ea][eb].remove()
# plot data on some axes
# note that axes on the first row (index=0) are gone
ax[2][0].plot([2,5,3,7])
ax[4][2].plot([2,3,7])
# make legend in upper-right axes (GridSpec's first row, last column)
# first index: 0
# second index: nn-1
rx, cx = 0, nn-1
ax[rx][cx] = fig.add_subplot(gs[rx,cx])
hdl = ax[rx][cx].scatter([10], [10], color="k", s=5, zorder=2, label="Targets")
ax[rx][cx].set_axis_off()
#ax[rx][cx].set_visible(True) # already True
ax[rx][cx].set_xticklabels([])
ax[rx][cx].set_yticklabels([])
# plot legend
plt.legend(bbox_to_anchor=(1.0, 1.0), loc='upper right', borderaxespad=0.)
fig.subplots_adjust(hspace=0.00, wspace=0.00)
plt.show
I have the following spreadsheet:
https://docs.google.com/spreadsheets/d/1Ib2Do3htfRg3NAuI-HyRA3MBM1XwUviFcAxlvF7q1J0/edit?usp=sharing
I have created 2 sparklines, 1 works, 1 doesn't. The one that does not work references the second column as the x-axis to calculate the slope. The slope is needed to give the graph some nice trending color.
My question is, how can I convert the second column into a serial [1, 2, 3, 4, 5]? So that when it is put as the x-axis, the slope would be calculated correctly. Of course, this conversion needs to happen within the formula itself. Thanks for any help.
try:
=ARRAYFORMULA(SPARKLINE(C2:C, {
"charttype", "line";
"color", IF(SLOPE(C2:C, ROW(B2:B)-1)>0, "lime", "red");
"linewidth", 2}))
I'm using OpenCV 3.0.0 with Python 2.7 and trying something that ought to be simple.
I want to stack images vertically.
This simple example:
import cv2
import numpy as np
comb = np.vstack((row_0, row_1))
cv2.imwrite('foo.png', comb)
consistently produces a foo.png that is drastically narrower (in the browser) than row_0 and row_1.
Details:
row_0.shape
(1074, 785, 3)
row_1.shape
(1187, 785, 3)
comb.shape
(2261, 785, 3)
If I look at row_0.png in the browser, it is WAY wider than foo.png.
Question
How can I alter my code so row_0.png is the same width as foo.png in the browser?
np.vstack does two things - make sure the inputs are at least 2d (here they are 3d), and joins them on axis=0 (rows). In other words
np.concatenate((row0, row1), axis=0)
That's what I see happening - two dimensions are the same, the first is the sum of the 2 inputs:
(1074, 785, 3)
+
(1187, 785, 3)
=
(2261, 785, 3)
If the comb looks narrower, it is probably because of scaling. The ratio of 2nd dim to 1st has gotten smaller; that's to be expected if you join 2 arrays in this way. And given the dimensions, that's the only possible way.
Viewed as arrays, comb has more rows, same number of columns. But if 2261 is the image display width, then relative height will be less.
I need to draw a bar graph for the values:
male=('2', '1', '2', '6', '6', '1') # list may increase
time=('Tue_Aug_13_04:37:40_2013', 'Mon_Jul__1_02:33:11_2013','Tue_Aug_13_04:37:40_2013', 'Thu_Jul__4_01:53:32_2013', 'Mon_Jul__1_10:05:55_2013','Mon_Jul__1_04:15:25_2013')# list may increase
female=(16, 11, 16, 12, 12, 11) # list may increase
Male in green colour, female in red colour as the image attached below:
The code which I tried:
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse, Polygon
fig = plt.figure()
ax1 = fig.add_subplot(131)
ax1.bar(male, color='red', edgecolor='black')
ax1.bar(bottom=range(female), color='blue', edgecolor='black')
ax1.set_xticks(time)
plt.show()
What modifications do I need to make in order to draw the bar graph as shown in the image attached for my values?
1.) I strongly suggest that you familiarize yourself with the python syntax:
What's the difference between lists enclosed by square brackets and parentheses?
What's the difference between '2' and 2?
2.) Make use of the matplotlib documentation to figure out the correct syntaxt for the plot commands you are using.
3.) In this particular case: To get you going, change your data to:
male=[2, 1, 2, 6, 6, 1] # list may increase
time=['Tue_Aug_13_04:37:40_2013', 'Mon_Jul__1_02:33:11_2013','Tue_Aug_13_04:37:40_2013', 'Thu_Jul__4_01:53:32_2013', 'Mon_Jul__1_10:05:55_2013','Mon_Jul__1_04:15:25_2013']# list may increase
female=[16, 11, 16, 12, 12, 11] # list may increase
Please examine carefully what has changed.
4.) The bar command you try to call has not enough input arguments. With the changed data from above, try this:
ax1.bar(range(len(time)),male,width=0.5, color='red', edgecolor='black')
ax1.bar(range(len(time)),female,width=0.5,bottom=male,color='blue', edgecolor='black')
What has changed?
you need the following inputs: left, height, width=0.8
you had only one of those
due to the fact that your dates are given as strings, you need a generic counter for the x-axis, hence the range(len(time)) to provide as many tics as there are entries in time.
now, you specify the height according to the values in male and female - none of which should be strings!
define a width
in your case, you want the bars to be stacked - therefore, specify the first set of values as bottom for the second
4.) Because time is made up of strings, you cannot use it for the ticks. Instead, try:
ax1.set_xticklabels(time,rotation=90)
Here, you use the strings from time as tick-labels. The rotation=90 is a nice feature so that the long strings do not overlap.
5.) If the labels are cut off by the plot window, try this:
plt.tight_layout()
plt.show()
This should get you back on track.
Good key words for a web-search inlcude:
matplotlib stacked bar
matplotlib tick labels rotation
matplotlib ticks date
I have a dataset like below in dictionary format,
data={'a': [10, 11,12,5,4,3,1], 'b': [7, 18,5,11,9,2,0]}
How we can make a scatter plot in python using rpy2? where x axis is the months and y axis are the mutiples of 5? we need to plot the graph with the above values where a and b are the data points
Months should be based on the length of each key i.e for the above data we have 7 months since we have 7 data points
This is a pretty involved data structure, and it's not completely clear what you're looking to do in terms of plotting. Here are a few hints, but it'd be easiest to help you if you would post the code you've tried but hasn't worked.
The R plot function takes two vectors corresponding to the x-axis values (months, here), and y-axis values (frequencies?). You'll want to go through your graph_data dictionary and calculate the y-axis values you want to plot for each month, and then make a corresponding vector for x containing the month numbers. For example:
x = [1,2,3,4]
y = [0.7, 0.9, 0.2, 0.4]
To do the plotting from rpy2, you'll need to convert the lists to vectors like so:
from rpy2 import robjects
x_vector = robjects.IntVector(x)
y_vector = robjects.FloatVector(y)
Then do the plotting:
robjects.r.plot(x_vector, y_vector, xlab="month", ylab="freq", main="")