Matplotlib, Set multiple parameters at once? - python

Is there a way to set parameters for multiple graphs at once - basically defining a default?
What I have right now:
fig = plt.figure()
ax1 = fig.add_subplot(313)
ax1.scatter(entries,gvalues[0], color='b', marker = '1')
ax1.scatter(entries,gvalues[1], color = 'g', marker = 'v')
xticks([z for z in range(N)], namelist)
ylabel('Label1', ha='center', labelpad=28)
ylim(0,)
ax2 = fig.add_subplot(312, sharex=ax1)
ax2.scatter(entries,gvalues[2], color = 'b', marker = '1')
ax2.scatter(entries,gvalues[3], color= 'g', marker = 'v')
ylabel('Label2', ha='center', labelpad=28)
setp(ax2.get_xticklabels(),visible=False)
ylim(0,)
I am going to have a handful of these graphs, and it would be great if I didn't have to set ha = 'center', labelpad = 28 and ylim(0,) everytime.
Cheers

You can use a dictionary to store your options as below:
font_options = dict(ha='center', labelpad=28)
ax1.set_ylabel('Label1', **font_options)
...
ax2.set_ylabel('Label2', **font_options)
The **font_options argument will unpack each of the key-value pairs in the dictionary and apply them within the ylabel function.
Similarly for the ylim option you can store your limits in a variable such as:
ylimit = 0
ylim(ylimit,)

Related

Data value of a variable in each marker within subplots

I'm developing the following function: extract_name_value() that generates a step chart taking the values of a pandas DataFrame in Python, for now it works fine, but I want to add the values of the variable points_axisyvalue or values_list to it in each marker: Script Here
I tried to use the following examples:Data value at each marker, Matplotlib scatter plot with different text at each data point or How to put individual tags for a matplotlib scatter plot?, which would be something like what I want; also I even tried using plt.annotate(), but the data of the values does not come out the way I want it, plus I think it would cover up the graph a lot and not appreciate well. Below I put the code in which I'm using plt.annotate():
# Function to extract the Name and Value attributes
def extract_name_value(signals_df, rootXML):
# print(signals_df)
names_list = [name for name in signals_df['Name'].unique()]
num_names_list = len(names_list)
num_axisx = len(signals_df["Name"])
values_list = [value for pos, value in enumerate(signals_df["Value"])]
print(values_list)
points_axisy = signals_df["Value"]
print(len(points_axisy))
colors = ['b', 'g', 'r', 'c', 'm', 'y']
# Creation Graphic
fig, ax = plt.subplots(nrows=num_names_list, figsize=(20, 30), sharex=True)
plt.suptitle(f'File XML: {rootXML}', fontsize=16, fontweight='bold', color='SteelBlue', position=(0.75, 0.95))
plt.xticks(np.arange(-1, num_axisx), color='SteelBlue', fontweight='bold')
labels = ['value: {0}'.format(j) for j in values_list]
print(labels)
i = 1
for pos, name in enumerate(names_list):
# get data
data = signals_df[signals_df["Name"] == name]["Value"]
print(data)
# get color
j = random.randint(0, len(colors) - 1)
# get plots by index = pos
x = np.hstack([-1, data.index.values, len(signals_df) - 1])
y = np.hstack([0, data.values, data.iloc[-1]])
ax[pos].plot(x, y, drawstyle='steps-post', marker='o', color=colors[j], linewidth=3)
ax[pos].set_ylabel(name, fontsize=8, fontweight='bold', color='SteelBlue', rotation=30, labelpad=35)
ax[pos].yaxis.set_major_formatter(ticker.FormatStrFormatter('%0.1f'))
ax[pos].yaxis.set_tick_params(labelsize=6)
ax[pos].grid(alpha=0.4)
i += 1
for label, x, y in zip(labels, x, y):
plt.annotate(label, xy=(x, y), xytext=(-20, 20), textcoords='offset points', ha='right', va='bottom', bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5),
arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=0'))
plt.show()
What I get is the annotations spliced and in different positions.
But, What does my code need to show each value at each point?
I've also been trying to use the code from the Matplotlib reference and couldn't get it done: Marker Reference. Thank you very much in advance, any comment helps.
You can use plt.annotate function in a loop to solve your problem.
I randomly generated some data and plotted it as a single plot. You can do the same inside a subplot, the function would be the same.
# sample data points for the plot
x=np.arange(1,10)
y=np.linspace(20,40,9)
plt.figure(figsize=[15,5],dpi=200)
plt.plot(x,y,drawstyle='steps-post', marker='o')
# using annotate function to show the changepoints in a loop
for i in range(len(x)):
# I rounded the y values as string and used the same x and y coords as the locations
# next we can give a constant offset points to offset the annotation from each value
# here I used (-20,20) as the offset values
plt.annotate(f"{str(round((y[i])))}",(x[i],y[i]),xycoords='data',
xytext=(-20,20), textcoords='offset points',color="r",fontsize=12,
arrowprops=dict(arrowstyle="->", color='black'))
You can remove the arrowprops if you don't want the arrows.
Edited
I used the example1.xml file in your GitHub repo and edited the function a bit. All I did was add a loop and an if-else condition to your function.
# Initial part is same as yours
names_list = [name for name in signals_df['Name'].unique()]
num_names_list = len(names_list)
num_axisx = len(signals_df["Name"])
values_list = [value for pos, value in enumerate(signals_df["Value"])]
points_axisy = signals_df["Value"]
colors = ['b', 'g', 'r', 'c', 'm', 'y']
# start new figure
plt.figure(figsize=[20,28],dpi=200)
#start a loop with the subplots
for i in range(len(names_list)):
# subplot has 14 rows, 1 column and the i+1 represents the i'th plot
plt.subplot(num_names_list,1,i+1)
# choose color
col=np.random.randint(0, len(colors) - 1)
# get the locations of the values with the similar name in your list
locs=signals_df['Name']==names_list[i]
# get the values in those locations
data=signals_df['Value'][locs]
# arrange the x and y coordinates
x = np.hstack([-1, data.index.values, len(signals_df) - 1])
y = np.hstack([0, data.values, data.iloc[-1]])
# plot the values as usual
plt.plot(x, y, drawstyle='steps-post', marker='o', color=colors[col], linewidth=3)
plt.ylabel(names_list[i], fontsize=8, fontweight='bold', color='SteelBlue', rotation=30, labelpad=35)
plt.grid(alpha=0.4)
# this loop is for annotating the values
for j in range(len(x)):
# I found it is better to alternate the position of the annotations
# so that they wont overlap for the adjacent values
if j%2==0:
# In this condition the xytext position is (-20,20)
# this posts the annotation box over the plot value
plt.annotate(f"Val={round((y[j]))}",(x[j],y[j]),xycoords='data',
xytext=(-20,20), textcoords='offset points',color="r",fontsize=8,
arrowprops=dict(arrowstyle="->", color='black'),
bbox=dict(boxstyle='round', pad=0.5, fc='yellow', alpha=0.5))
else:
# In this condition the xytext position is (-20,-20)
# this posts the annotation box under the plot value
plt.annotate(f"Val={round((y[j]))}",(x[j],y[j]),xycoords='data',
xytext=(-20,-20), textcoords='offset points',color="r",fontsize=8,
arrowprops=dict(arrowstyle="->", color='black'),
bbox=dict(boxstyle='round', pad=0.5, fc='yellow', alpha=0.5))
New Function Result
I hope that it is useful.
I think it should be quite close to what you are after. I randomly generate data, then annotate it using matplotlib.text. It's not very pretty, you might want to add some padding and more refinements, but I hope it gives a good idea!
If two points are too close, you might want to annotate one on the left, and the other one on the right, like I am doing for the first point. I have not seen such a situation in the examples that you have given, so it's not handled.
Function place_label(label, xy, position, ax, pad=0.01) places the label where you want it to be. The rest of the code is demonstrating that it works, using randomly generated data.
import random
import numpy as np
import matplotlib.pyplot as plt
# function that places the label give the desired position
def place_label(label, xy, position, ax, pad=0.01):
# annotate in the initial position, xy is the top right corner of the bounding box
t_ = ax.text(x=xy[0], y=xy[1], s=label, fontsize=16)
# find useful values
tbb = t_.get_window_extent(renderer=rend)
abb = ax.get_window_extent(renderer=rend)
a_xlim, a_ylim = ax.get_xlim(), a_.get_ylim()
# now adjust the position if needed
new_xy = [xy[0], xy[1]]
relative_width = tbb.width/abb.width * (a_xlim[1] - a_xlim[0])
pad_x = pad * (a_xlim[1] - a_xlim[0])
assert(position[0] in ['l', 'c', 'r'])
if position[0] == 'c':
new_xy[0] -= relative_width/2
elif position[0] == 'l':
new_xy[0] -= relative_width + pad_x
else:
new_xy[0] += pad_x
relative_height = tbb.height/abb.height * (a_ylim[1] - a_ylim[0])
pad_y = pad * (a_ylim[1] - a_ylim[0])
assert(position[1] in ['b', 'c', 't'])
if position[1] == 'c':
new_xy[1] -= relative_height/2
elif position[1] == 'b':
new_xy[1] -= relative_height + pad_y
else:
new_xy[1] += pad_y
t_.set_position(new_xy)
return t_
# generate data, plot it and annotate it!
axes_qty = 9
axes_gap = 0.035
fig = plt.figure(figsize=(10, 8))
ax = [plt.axes([axes_gap, axes_gap/2 + i*(1/axes_qty), 1-2*axes_gap, 1/axes_qty-axes_gap]) for i in range(axes_qty)]
rend = fig.canvas.get_renderer()
for a_ in ax:
x_ = [random.randint(0, 10) for _ in range(5)]
x_ = np.unique(x_)
y_ = [random.randint(0, 12) for _ in x_]
# as x is shared, we set the limits in advance, otherwise the adjustments won't be accurate
a_.set_xlim([-0.5, 10.5])
# plotting the data
data_ = [[x_[0], y_[0]]]
for i in range(1, len(x_)):
data_ += [[x_[i-1], y_[i]], [x_[i], y_[i]]]
a_.plot([d[0] for d in data_], [d[1] for d in data_])
mid_y = 0.5 * (a_.get_ylim()[0] + a_.get_ylim()[1])
# now let's label it
for i in range(len(x_)):
# decide what point we annotate
if i == 0:
xy = [x_ [0], y_[0]]
else:
xy = [x_[i-1], y_[i]]
# decide its position
position_0 = 'l' if i == 0 else 'r'
position_1 = 'b' if xy[1] > mid_y else 't'
place_label(label=str(xy[1]), xy=xy, position=position_0+position_1, ax=a_)
plt.show()

How to resize the x-axis and make it different from the y-axis Matplotlib

I have the following development that I am working on with ElementTree, Pandas and Matplotlib modules in Python:
def extract_name_value(signals_df):
#print(signals_df)
names_list = [name for name in signals_df['Name'].unique()]
num_names_list = len(names_list)
colors = ['b', 'g', 'r', 'c', 'm', 'y', 'k']
# Creation Graphic
fig = plt.figure(figsize=(18, 20))
plt.suptitle(f'File PXML: {rootXML}', fontsize=20, fontweight='bold', color='SteelBlue', position=(0.75, 0.90))
fig.tight_layout()
i = 1
for name in names_list:
# get data
data = signals_df[signals_df["Name"] == name]["Value"]
datax = signals_df["Name"]
# x = [n for n in range(len(data))]
x = [n for n in range(len(datax))]
print(x)
# get color
j = random.randint(0, len(colors) - 1)
# add subplots
ax = plt.subplot(num_names_list, 1, i)
ax.plot(x, data, drawstyle='steps', marker='o', color=colors[j], linewidth=3)
# plt.xticks(None)
ax.set_ylabel(name, fontsize=12, fontweight='bold', color='SteelBlue', rotation=50, labelpad=45)
ax.grid(alpha=0.4)
i += 1
plt.show()
I am getting the following error:
I have been looking for the error and I totally understand that the dimensions of x and y must be equal, but there is the possibility of making a graph where the x-axis is greater than the y-axis? and also the x-axis comes from a variable not related to the y-axis? how would this be?
The x-axis is the count of all the values it has in the Signal element of the xml file: I put it here because of how extensive it is and this value is larger than the y-axis, but how to contemplate the 3 values that I bring from the xml that are Singal Name, Signal Value as y-axis and Count of Signals as x-axis. I really appreciate your comments and help.
IIUC, you are trying to plot several stepped values agains their order of appearance (X-index) in XML file. Then you should plot against original dataframe's X values. I haven't changed your code much for style or such, just fixed a little.
import xml.etree.ElementTree as ET
import pandas as pd
from matplotlib import pyplot as plt
import random
file_xml = 'example_un_child4.xml'
def transfor_data_atri(rootXML):
file_xml = ET.parse(rootXML)
data_XML = [
{"Name": signal.attrib["Name"],
"Value": int(signal.attrib["Value"].split(' ')[0])
} for signal in file_xml.findall(".//Signal")
]
signals_df = pd.DataFrame(data_XML)
extract_name_value(signals_df)
def extract_name_value(signals_df):
#print(signals_df)
names_list = [name for name in signals_df['Name'].unique()]
num_names_list = len(names_list)
colors = ['b', 'g', 'r', 'c', 'm', 'y', 'k']
# Creation Graphic
#fig = plt.figure(figsize=(18, 20), sharex=True)
fig, ax = plt.subplots(nrows=num_names_list, figsize=(10, 15), sharex=True)
plt.suptitle(f'File PXML: {file_xml}', fontsize=20, fontweight='bold', color='SteelBlue', position=(0.75, 0.90))
#fig.tight_layout()
i = 1
for pos, name in enumerate(names_list):
# get data
data = signals_df[signals_df["Name"] == name]["Value"]
datax = signals_df["Name"]
# x = [n for n in range(len(data))]
#x = [n for n in range(len(datax))]
#print(x)
# get color
j = random.randint(0, len(colors) - 1)
# add subplots
#ax[pos] = plt.subplot(num_names_list, 1, i)
ax[pos].plot(data.index, data, drawstyle='steps', marker='o', color=colors[j], linewidth=3)
# plt.xticks(None)
ax[pos].set_ylabel(name, fontsize=12, fontweight='bold', color='SteelBlue', rotation=50, labelpad=45)
ax[pos].grid(alpha=0.4)
i += 1
fig.tight_layout()
plt.show()
transfor_data_atri(file_xml)

Matplotlib: Gridspec not displaying bar subplot

I have a 4x3 grid. I have 1 broken horizontal bar plot in the first row followed by 9 scatter plots. The height of the bar plot needs to be 2x height of the scatter plots. I am using gridspec to achieve this. However, it doesn't plot the bar plot completely. See picture below:
The complete bar plot looks like this
I am not sure why is this happening. Any suggestions?
Here's my code:
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import gridspec
#####Importing Data from csv file#####
dataset1 = np.genfromtxt('dataSet1.csv', dtype = float, delimiter = ',', skip_header = 1, names = ['a', 'b', 'c', 'x0'])
dataset2 = np.genfromtxt('dataSet2.csv', dtype = float, delimiter = ',', skip_header = 1, names = ['a', 'b', 'c', 'x0'])
dataset3 = np.genfromtxt('dataSet3.csv', dtype = float, delimiter = ',', skip_header = 1, names = ['a', 'b', 'c', 'x0'])
corr1 = np.corrcoef(dataset1['a'],dataset1['x0'])
corr2 = np.corrcoef(dataset1['b'],dataset1['x0'])
corr3 = np.corrcoef(dataset1['c'],dataset1['x0'])
corr4 = np.corrcoef(dataset2['a'],dataset2['x0'])
corr5 = np.corrcoef(dataset2['b'],dataset2['x0'])
corr6 = np.corrcoef(dataset2['c'],dataset2['x0'])
corr7 = np.corrcoef(dataset3['a'],dataset3['x0'])
corr8 = np.corrcoef(dataset3['b'],dataset3['x0'])
corr9 = np.corrcoef(dataset3['c'],dataset3['x0'])
fig = plt.figure(figsize = (8,8))
gs = gridspec.GridSpec(4, 3, height_ratios=[2,1,1,1])
def tornado1():
np.set_printoptions(precision=4)
variables = ['a1','b1','c1','a2','b2','c2','a3','b3','c3']
base = 0
values = np.array([corr1[0,1],corr2[0,1],corr3[0,1],
corr4[0,1],corr5[0,1],corr6[0,1],
corr7[0,1],corr8[0,1],corr9[0,1]])
variables=zip(*sorted(zip(variables, values),reverse = True, key=lambda x: abs(x[1])))[0]
values = sorted(values,key=abs, reverse=True)
# The y position for each variable
ys = range(len(values))[::-1] # top to bottom
# Plot the bars, one by one
for y, value in zip(ys, values):
high_width = base + value
# Each bar is a "broken" horizontal bar chart
ax1= plt.subplot(gs[1]).broken_barh(
[(base, high_width)],
(y - 0.4, 0.8),
facecolors=['red', 'red'], # Try different colors if you like
edgecolors=['black', 'black'],
linewidth=1,
)
# Draw a vertical line down the middle
plt.axvline(base, color='black')
# Position the x-axis on the top/bottom, hide all the other spines (=axis lines)
axes = plt.gca() # (gca = get current axes)
axes.spines['left'].set_visible(False)
axes.spines['right'].set_visible(False)
axes.spines['top'].set_visible(False)
axes.xaxis.set_ticks_position('bottom')
# Make the y-axis display the variables
plt.yticks(ys, variables)
plt.ylim(-2, len(variables))
plt.draw()
return
def correlation1():
corr1 = np.corrcoef(dataset1['a'],dataset1['x0'])
print corr1[0,1]
corr2 = np.corrcoef(dataset1['b'],dataset1['x0'])
print corr2[0,1]
corr3 = np.corrcoef(dataset1['c'],dataset1['x0'])
print corr3[0,1]
ax2=plt.subplot(gs[3])
ax2.scatter(dataset1['a'],dataset1['x0'],marker = '.')
ax2.set_xlabel('a1')
ax2.set_ylabel('x01')
ax3=plt.subplot(gs[4])
ax3.scatter(dataset1['b'],dataset1['x0'],marker = '.')
ax3.set_xlabel('b1')
#ax3.set_ylabel('x01')
ax4=plt.subplot(gs[5])
ax4.scatter(dataset1['c'],dataset1['x0'],marker = '.')
ax4.set_xlabel('c1')
#ax4.set_ylabel('x01')
ax5=fig.add_subplot(gs[6])
ax5.scatter(dataset2['a'],dataset2['x0'],marker = '.')
ax5.set_xlabel('a2')
ax5.set_ylabel('x02')
ax6=fig.add_subplot(gs[7])
ax6.scatter(dataset2['b'],dataset2['x0'],marker = '.')
ax6.set_xlabel('b2')
#ax6.set_ylabel('x02')
ax7=fig.add_subplot(gs[8])
ax7.scatter(dataset2['c'],dataset2['x0'],marker = '.')
ax7.set_xlabel('c2')
#ax7.set_ylabel('x02')
ax8=plt.subplot(gs[9])
ax8.scatter(dataset3['a'],dataset3['x0'],marker = '.')
ax8.set_xlabel('a3')
ax8.set_ylabel('x03')
ax9=plt.subplot(gs[10])
ax9.scatter(dataset3['b'],dataset3['x0'],marker = '.')
ax9.set_xlabel('b3')
#ax9.set_ylabel('x03')
ax10=plt.subplot(gs[11])
ax10.scatter(dataset3['c'],dataset3['x0'],marker = '.')
ax10.set_xlabel('c3')
#ax10.set_ylabel('x03')
plt.show()
return
tornado1()
correlation1()
plt.tight_layout()
plt.show()
Any help would be highly appreciated :-)
In the block of code:
# Plot the bars, one by one
for y, value in zip(ys, values):
high_width = base + value
# Each bar is a "broken" horizontal bar chart
ax1= plt.subplot(gs[1]).broken_barh(
[(base, high_width)],
(y - 0.4, 0.8),
facecolors=['red', 'red'], # Try different colors if you like
edgecolors=['black', 'black'],
linewidth=1,
)
You're reinitializing gs[1] on each loop so in the end, your plot only contains the last bar. You should try something like this instead:
# Plot the bars, one by one
ax1 = plt.subplot(gs[1])
for y, value in zip(ys, values):
high_width = base + value
# Each bar is a "broken" horizontal bar chart
ax1.broken_barh(
[(base, high_width)],
(y - 0.4, 0.8),
facecolors=['red', 'red'], # Try different colors if you like
edgecolors=['black', 'black'],
linewidth=1,
)
Hope that helps.

Adding colored boxes to axes in Python's matplotlib

Community,
Say I have created a scatter plot with Python's matplotlib:
plt.scatter(x, y)
Let's say this is the data:
Now, is there a way to add colored boxes on the axis (between given x-values, e.g.,: add a green box from x=-0.2 to x=0, add a ...) like this:
Including the text labels (at the mid-range I guess).
I am not even sure how to get started on this one to be honest (besides making the scatter plot).
Question
Can anyone at least direct me to a feature of matplotlib that does this (or any other Python package)?
Your help is much appreciated.
You probably want to go with matplotlib's text()
function. Maybe something like this,
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 1, 100)
y = np.sin(2*np.pi * x)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y, 'o')
ax.set_xlim(-0.2, 1.2)
ax.set_ylim(-1.5, 1.5)
x_ticks = ax.get_xticks()
y_ticks = ax.get_yticks()
# use len(x_ticks)-1 number of colors
colors = ['b', 'g', 'r', 'c', 'm', 'y', 'orange']
for i, x_tick in enumerate(x_ticks[:-1]):
ax.text(x_tick+0.03, y_ticks[0]-0.165, "text %i"%i,
bbox={'fc':colors[i], 'pad':10})
This code returns this image. You can adjust the padding and x,y position as necessary to achieve the exact look you're going for.
fig = plt.figure(figsize=(6,4))
plt.plot(np.arange(0,7,1),np.arange(0,7,1),linestyle='--', marker='o', color='b')
rect1 = plt.Rectangle((1.5,1.5),(0.7),(0.5), facecolor="grey",edgecolor="black",alpha=0.8)
rect2 = plt.Rectangle((2.5,2.5),(0.7),(0.5), facecolor="yellow",edgecolor="black",alpha=0.8)
rect3 = plt.Rectangle((3.5,3.5),(0.7),(0.5), facecolor="k",edgecolor="black",alpha=0.8)
plt.gca().add_patch(rect1)
plt.gca().add_patch(rect2)
plt.gca().add_patch(rect3)
plt.text(1.65,1.65,r"Grey",fontsize = 10,zorder = 5,color = 'k',fontweight = 'bold')
plt.text(2.55,2.65,r"Yellow",fontsize = 10,zorder = 5,color = 'k',fontweight = 'bold')
plt.text(3.555,3.65,r"Black",fontsize = 10,zorder = 5,color = 'white',fontweight = 'bold')

How to put the axis for two subplots separately?

I am trying to have two sub-plots in the figure in the Python Script. But I am not able to set the axis separately according to my inputs. Can anybody help me to set the x-axis, y-axis for each of the sub-plot separately?
I am including the piece of code that I have done, which was not giving me the result.
fig = plt.figure()
ax = plt.subplot(121) # To show the ascending order
plt.xlabel ('RF Input Power (dBm)', fontsize = 'small')
plt.ylabel ('Gain (dB)', fontsize = 'small')
tx = plt.title('Gain Vs Ascending RFInputAmpl for ' + str(measuredFrequencyUnderTest) + 'MHz', fontsize = 'small')
axPlotAxis = plt.axis([rfInputMin, rfInputMax, -20.0, 30.0])
# Now, Plot all the gain stages across the RFInput
ax.plot(rfInput_Plot, lna_Pre_Plot, color = 'r', marker = '+', label = 'lna_Pre')
ax.plot(rfInput_Plot, lna_Post_Plot, color = 'm', marker = 'x', label = 'lna_Post')
ax.plot(rfInput_Plot, sampler1_Plot, color = 'k', marker = '*', label = 'Sampler1')
ax.plot(rfInput_Plot, sampler2_Plot, color = 'c', marker = 's', label = 'Sampler2')
ax.plot(rfInput_Plot, vga_Plot, color = 'b', marker = 'p', label = 'VGA')
ax.plot(rfInput_Plot, dagc1_Plot, color = 'g', marker = 'H', label = 'DAGC1')
ax.plot(rfInput_Plot, dagc2_Plot, color = 'y', marker = 'v', label = 'DAGC2')
# Put the Legend
ax.legend(loc='upper center', bbox_to_anchor = (1.3, -0.05), shadow=True,numpoints = 1, prop = legend_font_props, ncol = 3)
# Now, come to the second plot
ay = plt.subplot(122) # To show the descending order
plt.xlabel ('RF Input Power (dBm)', fontsize = 'small')
plt.ylabel ('Gain (dB)', fontsize = 'small', horizontalalignment = 'left')
ty = plt.title('Gain Vs Descending RF Input for '+ str(measuredFrequencyUnderTest)+ 'MHz', fontsize = 'small')
# Now, fix the x axis here in descending order
plt.axis([rfInputMax, rfInputMin, y_Min_Value, y_Max_Value])
plt.minorticks_on()
Is there something wrong that I am performing? Pls help me to correct it.
You can set independent scales very easily (from an ipython -pylab session):
In [8]: ax = plt.subplot(121)
In [9]: ay = plt.subplot(122)
In [10]: ax.set_xlim((-1,2))
In [11]: ax.set_ylim((10,20))
In [12]: ay.set_xlim((-10,4))
In [13]: ay.set_ylim((3,5))

Categories

Resources