R: A 3d looking single dimension barplot - python

I tried with the package epade but I failed!
Example:
Each one of the x values defines the height of each bar (bars as many x values exist, with x height).
xa<-c(9.45,6.79,14.03,7.25,16.16,19.42,16.30,4.60,14.76,19.24,
16.04,7.80,13.16,10.00,15.76,16.29,19.52,27.22,7.74,6.75)
barplot(xa)
So I would like exactly the same plot in 3d looking fashion!
Is it possible?
UPDATED SOLUTION
This was done in Python, not in R :(
Here is the code:
# needed modules
import csv
import pandas as pandas
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
from scipy.interpolate import spline
from textwrap import wrap
from mpl_toolkits.mplot3d import proj3d
import pylab
import os
# we define some names in order to change only one
# 3 columnes are imported each time
# by changing col_inc from 0 to something
# we can define which range of columns will be imported
col_num = np.arange(2, 1001)
col_num_tuple = tuple(col_num)
cnt = col_num_tuple
cnt
# last counter col_inc = 279
col_inc = 273
str = 0 + col_inc
fin = 3 + col_inc
cols = cnt[str:fin]
cols
# importing a simple datafile, csv type. Data are comma seperated
# importing only 1st, 2nd and 4th columns
# We can call these data now by giving a new name, 'io'.
io = pandas.read_csv(
'/data.csv', sep=",", usecols=cols)
# Try to get the name of singer & the name of song
# in the first two rows
names = io[0:2]
nm = names
nm1 = np.array(nm[:], dtype='string')
nm_singer = nm1[0:1][0:2, 1][0]
nm_song = nm1[1:2][0:2, 1][0]
nm_singer
nm_song
nms = nm_singer + ' - ' + nm_song
# we drop nan values
io = io.dropna()
# we make this in order not change each time, the name of column
io_all = np.array(io[3:])
io_st = np.array(io_all[:, 0], dtype=float)
io_end = np.array(io_all[:, 1], dtype=float)
io_dur = np.array(io_all[:, 2], dtype=float)
io_all
io_st
io_end
io_dur
# We define a new name for the column that is named alice inside io dataset
result = io_dur
# we need to make these data 'array type'
result = np.array(result)
# we now define the dimensions of our figure/plot, as well its dpi
fig = plt.figure(figsize=(16, 8), dpi=150)
# This line defines our first plot
# Afterwards, the '112' will define our second plot.
ax1 = fig.add_subplot(111, projection='3d')
# ax1 = Axes3D(fig)
# we define here labels
xlabels = io_end
xpos = np.arange(xlabels.shape[0])
ylabels = np.array([''])
ypos = np.arange(ylabels.shape[0])
xposM, yposM = np.meshgrid(xpos, ypos, copy=False)
zpos = result
zpos = zpos.ravel()
# this defines the dimensions of the actual boxes
# you can play with these values.
dx = 0.7
dy = 0.7
dz = zpos
# here, we define ticks, they are placed in the 'middle' of each bar
ax1.w_xaxis.set_ticks(xpos + dx / 2.)
ax1.w_xaxis.set_ticklabels(xlabels, rotation='vertical')
ax1.w_yaxis.set_ticks(ypos + dy / 2.)
ax1.w_yaxis.set_ticklabels(ylabels)
# here we define the colors of the bars, rainbow style
# you can play with these numbers
values = np.linspace(0.2, 1., xposM.ravel().shape[0])
colors = cm.rainbow(values)
# figure subtitle
# fig.suptitle('test title', fontsize=20)
# here, we define in the x axis the size of its ticks, its numbers
ax1.tick_params(axis='x', which='major', pad=0, labelsize=7)
# Here, we define the limits of y axis,
# NOTE that this defines WHERE bars will be placed
# IN relation to the rest figure,
# their offset point
plt.ylim((-2, 5))
# this says if the grid will be printed
plt.grid(True)
# this defines the placement of the 3d plot in its placeholders,
# in the surrounding white space
# I was surprised! The below line is not needed at all!
# fig.subplots_adjust(left=0, right=0, bottom=0, top=0)
# this is the actual command to define the plot
# all 6 parameters that we previously defined, are placed here.
# colors is an extra parameter
ax1.bar3d(xposM.ravel(), yposM.ravel(), dz * 0, dx, dy, dz, color=colors)
# elevation and azimuth, basically, definition of the view angle
ax1.view_init(0, -95)
# here we define that we will place a second plot
# Neither this line is needed!
# ax1 = fig.add_subplot(112, projection='3d')
# To produce numbers from 0 according to how many data exist in 'result'
x = np.arange(0, len(result))
y = result
# I try to center the line in relation to the top of bars.
y += 5
# Produce more points in order to make the line to look nicer (300).
x_smooth = np.linspace(x.min(), x.max(), 300)
y_smooth = spline(x, y, x_smooth)
# smooth line sometimes went below zero in some extreme cases.
# Therefore I added this if statement to find these cases
# and increase the height of the smooth line so much points
# as the points that went below 0
if min(y_smooth) <= 0:
y -= (min(y_smooth))-1
y_smooth = spline(x, y, x_smooth)
# a trick to center the line to bars
x_smooth += 0.4
# here,i try to produce a 'z' array of so many zeros as the length
# of 'x_smooth line'
z = np.linspace(0, 0, len(x_smooth))
# here, we define the parameters of the second plot.
# ax1' symbol is duplicated
# in order to plot the line in the same plot with the barplot.
ax1.plot(x_smooth, z, y_smooth)
# this try to align the y title
ax1.annotate(
'\n'.join(wrap('Duration of each Rythm (in sec)', 20)),
xy=(0.20, 0.80), xytext=(0, 0), fontsize=8, color='steelblue',
style='italic',
xycoords='axes fraction', textcoords='offset points',
bbox=dict(facecolor='mistyrose', alpha=0.3),
horizontalalignment='center', verticalalignment='down')
# this try to align the x title
ax1.annotate(
'\n'.join(wrap('Where Rythm is broken (in sec)', 20)),
xy=(0.27, 0.06), xytext=(0, 0), fontsize=9, color='steelblue',
xycoords='axes fraction', textcoords='offset points',
bbox=dict(facecolor='peachpuff', alpha=0.3),
horizontalalignment='center', verticalalignment='down')
# this try to center the bottom title
ax1.annotate(
'\n'.join(wrap(nms, 100)), xy=(0.5, 0.07),
xytext=(0, 0), fontsize=11,
xycoords='axes fraction', textcoords='offset points',
bbox=dict(facecolor='mediumorchid', alpha=0.3),
horizontalalignment='center', verticalalignment='down')
# Eedefine path and filename in order to save in custom made filename
pathnm = '/'
filenm = nms
nflnm = '%s_3D.png' % filenm
npath = os.path.join(pathnm, nflnm)
# saving our plot
#fig.savefig(npath, bbox_inches='tight', pad_inches=0,figsize=(46,15),dpi=400)
plt.show(fig)
io[0:2]'code'

Related

Generate multi-line plot using cmap from pandas DataFrame with discrete legends for each line series

I have a dataframe such as below and I am trying to use the example plot code (given below) to generate a similar style line series plot for my dataframe.
df = pd.DataFrame({'x': np.linspace(0, 10, 100),
'run0_Y': np.sin(np.linspace(0, 10, 100)),
'run1_Y': np.cos(np.linspace(0, 10, 100)),
'run2_Y': np.cos(np.linspace(0, 10, 100)),
'run3_Y': np.arctan(np.linspace(0, 10, 100))
})
I would like to generate a plot like below (see code) but I want to
replace the colorbar with my dataframe headings ['run0_Y' ...
'run3_Y'] as legends for each color.
'run0_Y' and 'run1_Y' belongs to the same color but differentiated
with solid line '-k' and dashed line '--k'
I am stuck as to how to plot the line series from my dataframe and
associate each dataframe column to its column header in the colorbar
as legend.
Example plotting code:
import numpy as np
import matplotlib.pyplot as plt
# Use the spectral colormap for examples
cmap = plt.cm.Spectral
# Generate some fake data
N = 100
nlines = 10
x = np.linspace(-np.pi, np.pi, N)
print('x: \n', x)
y = np.linspace(-np.pi, np.pi, nlines)
print('y: \n', y)
# Use np.newaxis to create [N,1] and [1,Nlines] x and y arrays
# Then broadcasting to generate Z with shape [N,Nlines]
z = np.sin(x[:,np.newaxis] + y[np.newaxis,:]/4)
print('z \n', z)
# Use 0-1 values to generate the colors with the linspace method
line_colors = cmap(np.linspace(0,1,nlines))
# We have to generate our own axis to put the colorbar in
# otherwise it "steals" space from the current axis. Please
# let me know if anyone has found another way around this,
# because the custom axes generation is the only way I've
# figured out.
from matplotlib.gridspec import GridSpec
# fig = plt.figure(figsize = (12,6))
# nrows = 2
# gs = GridSpec(nrows,2,width_ratios=[50,1])
# ax = [plt.subplot(gs[i,0]) for i in range(nrows)]
# cbax1 = plt.subplot(gs[1,1])
# # First, plot lines w/ legend
# a = ax[0]
# a.set_title('Labeling with a legend')
# for i in range(nlines):
# a.plot(x, z[:,i], c=line_colors[i],lw=3,label='{:4.1f}'.format(y[i]))
# leg = a.legend(loc='center left', bbox_to_anchor=(1, 0.5), ncol=2)
# leg.set_title('Y')
# # Next, plot with colorbar
# a = ax[1]
# a.set_title('Labeling with a "continuous" colorbar')
# for i in range(nlines):
# a.plot(x, z[:,i], c=line_colors[i],lw=3,label='{:3.1f}'.format(y[i]))
# # Generate fake ScalarMappable for colorbar
# sm = plt.cm.ScalarMappable(cmap=cmap, norm=plt.Normalize(vmin=y[0],vmax=y[-1]))
# sm.set_array([]) # You have to set a dummy-array for this to work...
# cbar = plt.colorbar(sm, cax=cbax1)
# cbar.set_label('Y')
# cbar.set_ticks(y)
# cbar.set_ticklabels(['{:4.1f}'.format(yi) for yi in y]) # Make 'em nicer-looking
# # Moves colorbar closer to main axis by adjusting width-spacing between subplot axes.
# fig.subplots_adjust(wspace=0.05, hspace=0.4)
# # Set axis limits
# for a in ax:
# a.set_xlim(-np.pi, np.pi)
fig = plt.figure(figsize = (12,6))
nrows = 1
gs = GridSpec(nrows,2,width_ratios=[50,1])
ax = [plt.subplot(gs[i,0]) for i in range(nrows)]
cbax = [plt.subplot(gs[i,1]) for i in range(nrows)]
# We'll use the same fake ScalarMappable and colormap for each example
from matplotlib.colors import ListedColormap
cmap2 = ListedColormap(line_colors)
sm = plt.cm.ScalarMappable(cmap=cmap2,
norm=plt.Normalize(vmin=y[0],vmax=y[-1]))
sm.set_array([])
# # Discrete colorbar with default spacing
# a = ax[0]
# a.set_title('Labeling with a discrete colorbar')
# for i in range(nlines):
# a.plot(x, z[:,i], c=line_colors[i],lw=2,label='{:4.1}'.format(y[i]))
# cbar = plt.colorbar(sm, cax=cbax[0])
# cbar.set_label('Y')
# cbar.set_ticks(y)
# cbar.set_ticklabels(['{:4.1f}'.format(yi) for yi in y]) # Make 'em nicer-looking
# Discrete colorbar with centered ticks
# a = ax[1]
a = ax[0]
a.set_title('Labeling with a discrete colorbar & centered labels')
for i in range(nlines):
a.plot(x, z[:,i], c=line_colors[i],lw=2,label='{:4.1}'.format(y[i]))
# Generate custom bounds so that ticks are centered
dy = y[1]-y[0]
ybounds = np.linspace(y[0]-dy/2., y[-1]+dy/2., nlines+1)
cbar = plt.colorbar(sm, cax=cbax[0], boundaries=ybounds)
cbar.set_label('Y')
cbar.set_ticks(y)
cbar.set_ticklabels(['{:4.1f}'.format(yi) for yi in y]) # Make 'em nicer-looking
# Set axis limits
for a in ax:
a.set_xlim(-np.pi, np.pi)
# Moves colorbar closer to main axis by adjusting width-spacing between subplot axes.
fig.subplots_adjust(wspace=0.05, hspace=0.4)
plt.show()
source: https://pyhogs.github.io/colormap-examples.html

subplots, how to set the xlabel and xlim, but removing axis

I'd like to plot EEG data and get this result:
But I am stuck on how to display the x axis label and its xlim.
After reading other questions, which use set_visible(False), I cannot resolve my issue.
I write my code in order to be reproducible:
sfreq = 256
raw_data = np.random.rand(14, 1000 * sfreq)
duration = 10 # duration of the signal
start = 200 * sfreq
final = start + int(sfreq * duration)
channels = list(np.arange(1, len(channels) + 1 ))
fig, ax = plt.subplots(len(channels), 1, sharex=True, figsize=(10, 10))
for idx, node in enumerate(channels):
data = raw_data[idx, start:final]
times = np.arange(1, data.size + 1) / sfreq
ax[idx].plot(times, data, lw=1., ls='-', c='k')
ax[idx].axis('off') # to remove bounding subplot
ax[idx].set_yticks([]) # to remove values from y axis
ax[idx].text(-1, 0, node, fontsize=12) # write text
# plt.axis(True)
# plt.axes().get_xaxis().set_visible(True)
# plt.xlim([200, 220])
plt.xlabel('Time (seconds)', fontsize=12)
plt.tight_layout()
plt.show()
This is my result:
But I'd like this:
Here are some possible changes to the plot:
make the code more python by using zip instead of an index in the for loop
change the visibility of the "spines" (the lines surrounding the subplot) instead of use axis('off')
remove the padding (margins)
use the axes transform to position the text of the y-axis
...
import matplotlib.pyplot as plt
import numpy as np
sfreq = 256
raw_data = np.random.rand(14, 1000 * sfreq)
duration = 10 # duration of the signal
start = 200 * sfreq
final = start + int(sfreq * duration)
channels = np.arange(len(raw_data)) + 1
fig, axs = plt.subplots(len(channels), 1, sharex=True, figsize=(10, 10))
for ax, node, data in zip(axs, channels, raw_data):
data = data[start:final]
times = np.arange(1, data.size + 1) / sfreq
ax.plot(times, data, lw=1., ls='-', c='k')
ax.set_yticks([]) # remove y ticks
for sp in ax.spines:
ax.spines[sp].set_visible(False) # hide the 4 lines surrounding the subplot
ax.text(-0.01, 0.5, node, fontsize=12, ha='right', va='center', transform=ax.transAxes) # write text
ax.margins(x=0) # avoid the empty space left and right
if ax != axs[-1]:
# ax.tick_params(axis='x', length=0) # hide the tick marks
ax.tick_params(bottom=False) # no tick marks at the bottom
axs[-1].set_xlabel('Time (seconds)', fontsize=12, labelpad=-10) # use negative padding to get closer to the xaxis
axs[-1].set_xticks([0, duration])
axs[-1].set_xticklabels([start // sfreq, final // sfreq])
axs[-1].spines['bottom'].set_bounds([0, duration]) # only draw the spine between the two ticks
axs[-1].spines['bottom'].set_visible(True)
axs[-1].spines['bottom'].set_linewidth(2)
plt.tight_layout()
plt.show()

3D Plot of Multiple Time Series in Python

I've seen numerous examples of 3D plots using matplotlib/seaborn in Python but can't seem to get what I'm looking for; I have 50 or so timeseries that I would like to plot cleanly as in the following example below but with the name of the series on the axis; as an example I've marked in Goog, IBM, GE, Pepsi etc. Appreciate any pointers or examples. Thank you,
Example PLOT Click Here Please
Matplotlib has very rich gallery. I found this, you can only plot it once instead of animation. And manually put y-axis legend wherever you want.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
# Fixing random state for reproducibility
np.random.seed(19680801)
# Create new Figure with black background
fig = plt.figure(figsize=(12, 8))
# Add a subplot with no frame
ax = plt.subplot(111, frameon=False)
# Generate random data
data = np.random.uniform(0, 1, (64, 75))
X = np.linspace(-1, 1, data.shape[-1])
G = 1.5 * np.exp(-4 * X ** 2)
# Generate line plots
lines = []
for i in range(len(data)):
# Small reduction of the X extents to get a cheap perspective effect
xscale = 1 - i / 200.
# Same for linewidth (thicker strokes on bottom)
lw = 1.5 - i / 100.0
line, = ax.plot(xscale * X, i + G * data[i], color="b", lw=lw)
lines.append(line)
# Set y limit (or first line is cropped because of thickness)
ax.set_ylim(-1, 70)
# No ticks
ax.set_xticks([])
ax.set_yticks([])
# 2 part titles to get different font weights
ax.text(0.5, 1.0, "MATPLOTLIB ", transform=ax.transAxes,
ha="right", va="bottom", color="k",
family="sans-serif", fontweight="light", fontsize=16)
ax.text(0.5, 1.0, "UNCHAINED", transform=ax.transAxes,
ha="left", va="bottom", color="k",
family="sans-serif", fontweight="bold", fontsize=16)
def update(*args):
# Shift all data to the right
data[:, 1:] = data[:, :-1]
# Fill-in new values
data[:, 0] = np.random.uniform(0, 1, len(data))
# Update data
for i in range(len(data)):
lines[i].set_ydata(i + G * data[i])
# Return modified artists
return lines
# Construct the animation, using the update function as the animation director.
anim = animation.FuncAnimation(fig, update, interval=10)
plt.show()

Loop to create subplot /Python

i have a little problem to create a subplot loop.
The following code show my result for one plot.... So it starts with a dayloop than with a hour loop (8 timesteps).
If i run the code i get a nice QUiver plot with the colorbar.
for dd in range(1,15):
day=str(dd)
readfile=fns[files_indizes[dd]]
if dd < 10:
nc_u_comp = NetCDFFile(ROOT+u_comp1+'0'+day+comp)
nc_v_comp = NetCDFFile(ROOT+v_comp1+'0'+day+comp)
else:
nc_u_comp = NetCDFFile(ROOT+u_comp1+day+comp)
nc_v_comp = NetCDFFile(ROOT+v_comp1+day+comp)
time = nc_u_comp.variables['time'][:]
index=readfile.find(comp)
index=index+len(comp)
date=readfile[index-14:index-6]
plt.clf()
for tt in range(0,len(time)):
if tt < 10:
h =str(0)+str(tt)
else:
h=str(tt)
varU=nc_u_comp.variables['u10'][tt,:,:]
varV=nc_v_comp.variables['v10'][tt,:,:]
lat = nc_u_comp.variables['latitude'][:]
lon = nc_u_comp.variables['longitude'][:]
plt.rcParams["figure.figsize"] = [10,10]
#plane projection of the world
#map with box size (defintion on the top)
box = sgeom.box(minx=llcrnrlon, maxx=urcrnrlon, miny=llcrnrlat, maxy=urcrnrlat)
x0, y0, x1, y1 = box.bounds
#Map plot. The middel of the map is central_longitude
#proj = ccrs.PlateCarree(central_longitude=0)
proj=ccrs.PlateCarree()
#Change middelpoint of the map
box_proj = ccrs.PlateCarree(central_longitude=0)
ax2 = plt.axes(projection=proj)
ax2.set_extent([x0, x1, y0, y1], box_proj)
ax2.add_feature(cartopy.feature.BORDERS, linestyle='-', alpha=.5)
ax2.coastlines(resolution='50m')
#Definition of the scale_bar
gl = ax2.gridlines(ccrs.PlateCarree(), \
linestyle='--', alpha=1, linewidth=0.5, draw_labels=True)
gl.xlabels_top = False
gl.ylabels_right = False
gl.xformatter = LONGITUDE_FORMATTER
gl.yformatter = LATITUDE_FORMATTER
magnitude = (varU ** 2 + varV ** 2) ** 0.5
strm =plt.streamplot(lon , lat , varU, varV, linewidth=2, density=2, color=magnitude)
cbar= plt.colorbar()
cbar.set_label('$m/s$')
name='Wind in 10 m '+ date + h+' UTC'
ax2.set_aspect('auto')
plt.title(name, y=1)
Now i want to create an 2x4 Subplot array with a colorbar allocate to the complete Subplot array.
I find some infromation in the internet, but it doesn't run with my code. Maybe someone can help me?
This shows how to plot an array of simple Cartopy maps in 4 rows 2 columns. Also shows how to plot a colorbar to accompany the maps array. Hope it helps.
import numpy as np
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
import matplotlib as mpl
# create figure with figsize big enough to accomodate all maps, labels, etc.
fig = plt.figure(figsize=(8, 10), tight_layout=False)
# define plot array's arrangement
columns = 2
rows = 4
# set projection to use
projex = ccrs.PlateCarree()
# set the colormap and norm for
# the colorbar to use
cmap1 = mpl.cm.magma
norm1 = mpl.colors.Normalize(vmin=0, vmax=100)
def plotmymap(axs):
# your plot specs of each map should replace this
img = np.random.randint(100, size=(15, 30)) # 2d array of random values (1-100)
# render image on current axis
plims = plt.imshow(img, extent=[-180,180,-90,90], alpha=0.5, cmap=cmap1, norm=norm1)
axs.set_global()
axs.coastlines()
# add title to the map
axs.set_title("Map_"+str(i))
return plims # for use by colorbar
for i in range(1, columns*rows +1):
# add a subplot into the array of plots
ax = fig.add_subplot(rows, columns, i, projection=projex)
plims = plotmymap(ax) # a simple maps is created on subplot
# add a subplot for vertical colorbar
bottom, top = 0.1, 0.9
left, right = 0.1, 0.8
fig.subplots_adjust(top=top, bottom=bottom, left=left, right=right, hspace=0.15, wspace=0.25)
cbar_ax = fig.add_axes([0.85, bottom, 0.05, top-bottom])
fig.colorbar(plims, cax=cbar_ax) # plot colorbar
plt.show() # this plot all the maps
The resulting plots:

How to adjust table for a plot? More space for table and graph matplotlib python

I want to separate or increase the distance of my table and my graph so they don't layover. I thought of increasing the size to right and put the table there but I can't seem to make it work, and I can't find a way to offset the table by 1 line.
Graph
global dataread
global top4
global iV
top4mod = [] #holder for table, combines amplitude and frequency (bin*3.90Hz)
plt.plot(x1, fy1, '-') #plot x-y
plt.axis([0, 500, 0, 1.2]) #range for x-y plot
plt.xlabel('Hz')
columns = ('Frequency','Hz')
rows = ['# %d' % p for p in (1,2,3,4)] #top4
colors = 'C0'
print(len(rows))
print(len(str(top4)))
print(top4)
iV=[d*bins for d in iV] # convert bins into frequency
i=0;
FirstCol = [4, 3, 2, 1]
while i < 4:
Table.append([iV[i]] + [top4[i]])#[FirstCol[i]]
i = i+1
cell_text = []
n_rows = len(Table)
index = np.arange(len(columns)) + 1 #0.3 orginal
bar_width = 0.4
y_offset = np.array([0.0] * len(columns))
for row in range(n_rows):
#plt.bar(index, Table[row], bar_width, bottom=y_offset, color='C0') #dont use this
y_offset = y_offset + Table[row]
cell_text.append(['%1.1f' % p for p in y_offset])
the_table = plt.table(cellText=Table,rowLabels=rows, colLabels=columns,loc='bottom')
#plt.figure(figsize=(7,8))
# Adjust layout to make room for the table:
plt.subplots_adjust(bottom=0.2) #left=0.2, bottom=0.2
plt.show() #display plot
Using bbox
You can set the position of the table using the bbox argument. It expects either a bbox instance or a 4-tuple of values (left, bottom, width, height), which are in axes coordinates. E.g.
plt.table(..., bbox=[0.0,-0.5,1,0.3])
produces a table that is as wide as the axes (left=0, width=1) but positionned below the axes (bottom=-0.5, height=0.3).
import numpy as np
import matplotlib.pyplot as plt
data = np.random.rand(4,2)
columns = ('Frequency','Hz')
rows = ['# %d' % p for p in (1,2,3,4)]
plt.plot(data[:,0], data[:,1], '-') #plot x-y
plt.axis([0, 1, 0, 1.2]) #range for x-y plot
plt.xlabel('Hz')
the_table = plt.table(cellText=data,rowLabels=rows, colLabels=columns,
loc='bottom', bbox=[0.0,-0.45,1,.28])
plt.subplots_adjust(bottom=0.3)
plt.show()
Create dedicated axes
You can also create an axes (tabax) to put the table into. You would then set the loc to "center", turn the axis spines off and only use a very small subplots_adjust bottom parameter.
import numpy as np
import matplotlib.pyplot as plt
data = np.random.rand(4,2)
columns = ('Frequency','Hz')
rows = ['# %d' % p for p in (1,2,3,4)]
fig, (ax, tabax) = plt.subplots(nrows=2)
ax.plot(data[:,0], data[:,1], '-') #plot x-y
ax.axis([0, 1, 0, 1.2]) #range for x-y plot
ax.set_xlabel('Hz')
tabax.axis("off")
the_table = tabax.table(cellText=data,rowLabels=rows, colLabels=columns,
loc='center')
plt.subplots_adjust(bottom=0.05)
plt.show()

Categories