I have a 16 subplots and want to include following in each subplot:
ax1.axvline(x=0.5, ymin=0.0, ymax=1.0, color='k', linestyle='--', alpha=0.3)
ax1.axhline(y=0.5, xmin=0.0, xmax=1.0, color='k', linestyle='--', alpha=0.3)
Running a loop to have them for all subplots seems more feasible rather to have 32 lines, but simple string concatenation isn't working such as
for i in xrange(1,17,1):
# then try to use i for each ax -- this isn't practical
Any suggestions?
You kinda got everything written already...
from matplotlib import pyplot as plt
f, ax = plt.subplots(17)
for i in range(17):
ax[i].axvline(x=0.5, ymin=0.0, ymax=1.0, color='k', linestyle='--', alpha=0.3)
ax[i].axhline(y=0.5, xmin=0.0, xmax=1.0, color='k', linestyle='--', alpha=0.3)
Related
I am trying to do EDA with the Kaggle dataset link
I made a plot with 3 subplots and have plotted 3 vertical lines on the basis of mean, median and mode. is there any way to show these 3 lines in a legend?
This is my code
def plott(data):
fig, axes = plt.subplots(3, sharex=True, figsize=(15, 15),gridspec_kw={"height_ratios": (1, 0.2, 0.6)})
fig.suptitle('Spread of Data for ' + data.name, fontsize=20, fontweight='bold')
sns.histplot(data, kde=True, binwidth=1, ax=axes[0])
sns.boxplot(x=data, orient='h', ax=axes[1])
sns.violinplot(x=data, ax=axes[2])
axes[0].set_xlabel('')
axes[1].set_xlabel('')
axes[2].set_xlabel('')
axes[0].axvline(data.mean(), color='r', linewidth=2, linestyle='solid')
axes[0].axvline(data.median(), color='r', linewidth=2, linestyle='dashed')
axes[0].axvline(data.mode()[0], color='r', linewidth=2, linestyle='dotted')
axes[1].axvline(data.mean(), color='r', linewidth=2, linestyle='solid')
axes[1].axvline(data.median(), color='r', linewidth=2, linestyle='dashed')
axes[1].axvline(data.mode()[0], color='r', linewidth=2, linestyle='dotted')
axes[2].axvline(data.mean(), color='r', linewidth=2, linestyle='solid')
axes[2].axvline(data.median(), color='r', linewidth=2, linestyle='dashed')
axes[2].axvline(data.mode()[0], color='r', linewidth=2, linestyle='dotted')
axes[0].tick_params(axis='both', which='both', labelsize=10, labelbottom=True)
axes[1].tick_params(axis='both', which='both', labelsize=10, labelbottom=True)
axes[2].tick_params(axis='both', which='both', labelsize=10, labelbottom=True)
plott(df['Age'])
This is the resulting plot
Is there a way to add the legend in here in accordance to the 3 vertical lines
like this with each line type denoting the value?
Also, how to add more values in x axis of all three graphs?
like make it interval of 5 or 2 years apart?
Thanks
Give the axvlines a "label" value, then call plt.legend after plotting it.
Example:
import matplotlib.pyplot as plt
plt.plot([1,2,3],[1,2,3],label="Test")
plt.axvline(x=0.22058956, label="Test2", color="red")
plt.legend()
Output:
My x-axis minor gridlines are not showing, this is my code
ax = plt.gca()
ax.minorticks_on()
plt.semilogx(data_x1,data_y1,"red")
plt.semilogx(data_x2,data_y2,"blue")
ax.grid(b=True, which='major',axis="both", color='k', linestyle='-', linewidth=0.5)
ax.grid(b=True, which='minor',axis="both", color='k', linestyle='-', linewidth=0.2)
plt.xlabel("frequency(Hz)")
plt.ylabel("Iramp(dB)")
plt.show()
enter image description here
Either I'm not sure of what you want, or your code is actually working correctly. The minor grid lines are those between the powers of 10. I made a little example to show a comparison of your plot with the minor grid lines on and off.
import numpy as np
import matplotlib.pyplot as plt
data_x1 = np.linspace(0,2,10)
data_x2 = np.linspace(0,4,10)
data_y1 = np.random.rand(10)
data_y2 = np.random.rand(10)
fig, axall =plt.subplots(1,2, figsize=(10,5))
# your code with some changes
ax = axall[0]
ax.minorticks_on()
ax.semilogx(data_x1,data_y1,"red")
ax.semilogx(data_x2,data_y2,"blue")
ax.grid(b=True, which='major',axis="both", color='k', linestyle='-', linewidth=0.5)
ax.grid(b=True, which='minor',axis="both", color='k', linestyle='-', linewidth=0.2)
ax.set_xlabel("frequency(Hz)")
ax.set_ylabel("Iramp(dB)")
# code to make the plot on the right.
ax = axall[1]
ax.minorticks_on()
ax.semilogx(data_x1,data_y1,"red")
ax.semilogx(data_x2,data_y2,"blue")
ax.grid(b=True, which='major',axis="both", color='k', linestyle='-', linewidth=0.5)
# ax.grid(b=True, which='minor',axis="both", color='k', linestyle='-', linewidth=0.2)
ax.set_xlabel("frequency(Hz)")
ax.set_ylabel("Iramp(dB)")
plt.show()
Note how I commented out your minor grid lines.
I'm trying to customize my plot, everything works fine except plotting the log grid. Any idea how to fix the issue?
Fig_Z21 = plt.figure()
plt.loglog(Z21['Frequency']/10e5, Z21['Z21_Mag'], label='Z21')
plt.gca().set_axis_bgcolor('white')
plt.grid(True, which='majorminor', color='k', linestyle='-', linewidth=0.4)
plt.gca().spines['bottom'].set_color('black')
plt.gca().spines['top'].set_color('black')
plt.gca().spines['left'].set_color('black')
plt.gca().spines['right'].set_color('black')
plt.gca().yaxis.label.set_color('black')
plt.gca().xaxis.label.set_color('black')
plt.gca().tick_params(axis='x', colors='black')
plt.gca().tick_params(axis='y', colors='black')
plt.rcParams['text.usetex'] = False #Let TeX do the typsetting
plt.xlabel('Frequency [MHz]', fontsize=12)
plt.ylabel('Magnitude', fontsize=12)
plt.show()
Try to use both as value of which in plt.grid:
plt.grid(True, which='both', color='k', linestyle='-', linewidth=0.4)
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()
I have the following code in my IPython notebook:
import matplotlib.pyplot as plt
plt.setp(plt.xticks()[1], rotation=45)
plt.figure(figsize=(17, 10)) # <--- This is the problematic line!!!!!!!!!!!!!
plt.plot_date(df['date'],df['x'], color='black', linestyle='-')
plt.plot_date(df['date'],df['y'], color='red', linestyle='-')
plt.plot_date(df['date'],df['z'], color='green', linestyle='-')
In the above example df is pandas data frame.
Without the marked line (containig figsize) the plot is too small. With the mentioned line I have an increased image as I want but before it I have an additional empty plot.
Does anybody know why it happens an how this problem can be resolved?
Try reversing the first two lines after the import. plt.setp is opening a figure.
here's how I would do this:
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(17, 10))
plt.setp(plt.xticks()[1], rotation=45)
ax.plot_date(df['date'],df['x'], color='black', linestyle='-')
ax.plot_date(df['date'],df['y'], color='red', linestyle='-')
ax.plot_date(df['date'],df['z'], color='green', linestyle='-')
It's a good practice to explicitly create and operate on your your Figure and Axes objects.