Subplot date formatting in Axis - python

I have a 2x2 graph with date in x-axis in both graphs. I have used datetime.strptime to bring a string into type = datetime.datetime object format.
However I am planning to have some 12 subplots and doing this the following way seems messy.
Is there a better 'pythonic' way?
This is what I have:
xx.xaxis.set_major_formatter(mdates.DateFormatter('%d/%m/%y %H:%M'))
plt.grid(True)
plt.ylabel('paramA',fontsize=8, color = "blue")
plt.tick_params(axis='both', which='major', labelsize=8)
plt.plot(date_list, myarray[:,0], '-b', label='paramA')
plt.setp(plt.xticks()[1], rotation=30, ha='right') # ha is the same as horizontalalignment
xx = plt.subplot(2,1,2)
xx.xaxis.set_major_formatter(mdates.DateFormatter('%d/%m/%y %H:%M'))
plt.grid(True)
plt.ylabel('paramB', 'amount of virtual mem',fontsize=8, color = "blue")
plt.tick_params(axis='both', which='major', labelsize=8)
plt.plot(date_list, myarray[:,1], '-y', label='paramB')plt.setp(plt.xticks()[1], rotation=30, ha='right') # ha is the same as horizontalalignment ```
PS: Initially I tried defining the plot as follows. This however did not work:
fig, axs = plt.subplots(2,1,figsize=(15,15))
plt.title('My graph')
for ax in enumerate(axs):
ax.xaxis.set_major_formatter(mdates.DateFormatter('%d/%m/%y %H:%M:%S'))

You failed to provide any data or a Minimal, Complete, and Verifiable example. Nevertheless, something like this should work. You can extend it to your real case by using desired number of rows and columns in the first command.
fig, axes = plt.subplots(nrows=2, ncols=3)
labels = ['paramA', 'paramB', 'paramC', 'paramD', 'paramE', 'paramF']
for i, ax in enumerate(axes.flatten()):
ax.xaxis.set_major_formatter(mdates.DateFormatter('%d/%m/%y %H:%M'))
ax.grid(True)
ax.set_ylabel(labels[i], fontsize=8, color="blue")
ax.tick_params(axis='both', which='major', labelsize=8)
ax.plot(date_list, myarray[:,i], '-b', label=labels[i])
plt.setp(plt.xticks()[1], rotation=30, ha='right') # ha is the same as horizontalalignment
EDIT:
Change your code to
fig, axs = plt.subplots(2,1,figsize=(15,15))
plt.title('My graph')
for ax in axs:
ax.xaxis.set_major_formatter(mdates.DateFormatter('%d/%m/%y %H:%M:%S'))

Related

change prophet scatter plot colors

hello im ussing fb prophet and changing old white layout for a better experience, i manage to change background and line colors in 'plot.py' , but cant change black scatters as seen on pic.
allready make a search but dont find a way
how can i change it?
if ax is None:
fig = plt.figure(facecolor='w', figsize=figsize)
ax = fig.add_subplot(111)
else:
fig = ax.get_figure()
fcst_t = fcst['ds'].dt.to_pydatetime()
ax.plot(m.history['ds'].dt.to_pydatetime(), m.history['y'], 'k.')
ax.plot(fcst_t, fcst['yhat'], ls='-', c='#0072B2')
if 'cap' in fcst and plot_cap:
ax.plot(fcst_t, fcst['cap'], ls='--', c='k')
if m.logistic_floor and 'floor' in fcst and plot_cap:
ax.plot(fcst_t, fcst['floor'], ls='--', c='k')
if uncertainty and m.uncertainty_samples:
ax.fill_between(fcst_t, fcst['yhat_lower'], fcst['yhat_upper'],
color='#ffffff', alpha=0.2)
# Specify formatting to workaround matplotlib issue #12925
locator = AutoDateLocator(interval_multiples=False)
formatter = AutoDateFormatter(locator)
ax.xaxis.set_major_locator(locator)
ax.xaxis.set_major_formatter(formatter)
ax.grid(True, which='major', c='white', ls='-', lw=1, alpha=0.2)
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
fig.tight_layout()
return fig
my plot

Bar plot Matplotlib : Date interval (xaxis) issue with twinx

I don't understand why my piece of code doesn't work. I would like to have an x axis with an interval of 1.
df['Dates'] = pd.to_datetime(df.Dates)
fig, ax = plt.subplots(figsize=(16, 9))
ax.bar(df['Dates'],
df['Score'],
color='blue',
width=2)
date_form = DateFormatter("%d/%m/%Y")
ax.xaxis.set_major_formatter(date_form)
ax.xaxis.set_major_locator(mdates.DayLocator(interval=1))
ax2=ax.twinx()
ax2.plot(df['Dates'],
df['Price'],
color = 'black')
plt.show()
Currently, ax's date formatting just gets overridden by ax2.plot, so you should apply the date formatter to ax2 instead of ax. Also autofmt_xdate is useful for rotating the date labels:
df['Dates'] = pd.to_datetime(df['Dates'])
fig, ax = plt.subplots(figsize=(16, 9))
ax.bar(df['Dates'], df['Score'], color='blue', width=1)
ax2 = ax.twinx()
ax2.plot(df['Dates'], df['Price'], color='black')
# apply the date formatting to ax2 instead of ax
date_form = DateFormatter('%d/%m/%Y')
ax2.xaxis.set_major_formatter(date_form)
ax2.xaxis.set_major_locator(mdates.DayLocator(interval=1))
# rotate the date labels
fig.autofmt_xdate(ha='center', rotation=90)
This is the output with some random data (in the future it's recommended to paste data as text so we can directly copy the real data):

matplotlib subplots empty when attempting to change font size of axes ticks

I had a script for plotting a single plot and adapted it for 2 subplots. When attempting to change the font size of the axes ticks via tick_params, all I get is a single empty plot. I've isolated this issue to the calling of this function. The following MWE runs fine with the tick_params calls commented out, but produces an incorrect figure if they're used. How can I modify this code to work with the subplots?
x = np.linspace(0.0, 1.0, 100)
y = x
fig = plt.figure()
plt.subplot(1,2,1)
plt.plot(x, y)
plt.xlabel('x', fontsize=16)
plt.ylabel('y', fontsize=16)
mystr = 'Some plot 1'
plt.title(mystr, fontsize=16)
# plt.axes().tick_params(axis='both', which='major', labelsize=16)
# plt.axes().tick_params(axis='both', which='minor', labelsize=16)
plt.grid()
plt.subplot(1,2,2)
plt.plot(x, y)
plt.xlabel('x', fontsize=16)
plt.ylabel('y', fontsize=16)
mystr = 'Some plot 2'
plt.title(mystr, fontsize=16)
# plt.axes().tick_params(axis='both', which='major', labelsize=16)
# plt.axes().tick_params(axis='both', which='minor', labelsize=16)
plt.grid()
plt.show()
Instead of accessing the subplot by plt.subplot(), access the axes._subplots.AxesSubplot individually.
I would try something like this:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0.0, 1.0, 100)
y = x
fig, ax = plt.subplots(1, 2)
ax[0].plot(x, y)
ax[0].set_title('Some plot 1', fontsize=16)
ax[0].set_xlabel('x', fontsize=16)
ax[0].set_ylabel('y', fontsize=16)
ax[0].tick_params(axis="x", labelsize=16)
ax[0].tick_params(axis="y", labelsize=16)
ax[0].grid()
ax[1].plot(x, y)
ax[1].set_title('Some plot 2', fontsize=16)
ax[1].set_xlabel('x', fontsize=16)
ax[1].set_ylabel('y', fontsize=16)
ax[1].tick_params(axis="x", labelsize=16)
ax[1].tick_params(axis="y", labelsize=16)
ax[1].grid()
A very similar question was actually asked on the official matplotlib GitHub repository. So if you like to have a more detailed look on why subplots work this way, you might want to read this issue.
Also, I would like to add: in your example, the figures slightly overlap. This could be solved by calling fig.tight_layout() after you defined your subplots.

X-axis minor gridlines still not showing even after trying all solutions

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.

Set minor ticks in all log-log subplots

I have a figure with two subplots in log-log scale. I would like to plot the minor ticks as well. Even though I have applied different solutions from Stack Overflow, my figure does not look as I want.
One of the solutions I have modified comes from ImportanceOfBeingErnest and the code looks like this:
fig, ((ax1, ax2)) = plt.subplots(1, 2, figsize=(8, 5), sharey=True)
# First plot
ax1.loglog(PLOT1['X'], PLOT1['Y'], 'o',
markerfacecolor='red', markeredgecolor='red', markeredgewidth=1,
markersize=1.5, alpha=0.2)
ax1.set(xlim=(1e-4, 1e4), ylim=(1e-8, 1e2))
ax1.set_xscale("log"); ax1.set_yscale("log")
ax1.xaxis.set_major_locator(matplotlib.ticker.LogLocator(base=10.0, numticks=25))
ax1.yaxis.set_major_locator(matplotlib.ticker.LogLocator(base=10.0, numticks=25))
locmaj = matplotlib.ticker.LogLocator(base=10,numticks=25)
ax1.xaxis.set_major_locator(locmaj)
locmin = matplotlib.ticker.LogLocator(base=10.0,subs=(0.2,0.4,0.6,0.8),numticks=25)
ax1.xaxis.set_minor_locator(locmin)
ax1.xaxis.set_minor_formatter(matplotlib.ticker.NullFormatter())
locmaj = matplotlib.ticker.LogLocator(base=10,numticks=25)
ax1.yaxis.set_major_locator(locmaj)
locmin = matplotlib.ticker.LogLocator(base=10.0,subs=(0.2,0.4,0.6,0.8),numticks=25)
ax1.yaxis.set_minor_locator(locmin)
ax1.yaxis.set_minor_formatter(matplotlib.ticker.NullFormatter())
ax1.set_xlabel('X values', fontsize=10, fontweight='bold')
ax1.set_ylabel('Y values', fontsize=10, fontweight='bold')
# Plot 2
ax2.loglog(PLOT2['X'], PLOT2['Y'], 'o',
markerfacecolor='blue', markeredgecolor='blue', markeredgewidth=1,
markersize=1.5, alpha=0.2)
ax2.set(xlim=(1e-4, 1e4), ylim=(1e-8, 1e2))
ax2.xaxis.set_major_locator(matplotlib.ticker.LogLocator(base=10.0, numticks=25))
ax2.yaxis.set_major_locator(matplotlib.ticker.LogLocator(base=10.0, numticks=25))
locmaj = matplotlib.ticker.LogLocator(base=10,numticks=25)
ax2.xaxis.set_major_locator(locmaj)
ax2.yaxis.set_major_locator(locmaj)
locmin = matplotlib.ticker.LogLocator(base=10.0,subs=(0.2,0.4,0.6,0.8),numticks=25)
ax2.xaxis.set_minor_locator(locmin)
ax2.yaxis.set_minor_locator(locmin)
ax2.xaxis.set_minor_formatter(matplotlib.ticker.NullFormatter())
ax2.yaxis.set_minor_formatter(matplotlib.ticker.NullFormatter())
ax2.set_xlabel('X values', fontsize=10, fontweight='bold')
ax2.set_ylabel('Y values', fontsize=10, fontweight='bold')
ax2.minorticks_on()
plt.show()
The plot I get is the following. As you can see, the minor ticks only appear on the x-axis from ax1.
How can I set the minor ticks in both subplots and both axis (x and y)?
Thank you so much.

Categories

Resources