I have a code that reads images from folders and annotates the images. I have about 10K images of size 3K x 3K. I apply cell detection, and I put an annotation on the images. For simplicity, I in the snapshot code provided below, the code generates a random image and random annotations with X and Y location.
The code works fine, in windows 10, with python 3.6 for both multiprocessing and without multiprocessing. However, when I submit to the HPC server with ubuntu 18.04 and Python 3.6, I am getting memory error with Matplotlib. I have tried the following, but no luck in resolving the problem.
* plt.close(fig)
* plt.figure().clear()
* plt.clf()
* plt.close()
'''
import os
import matplotlib.pyplot as plot
import pandas as pd
import multiprocessing as mp
import numpy as np
import seaborn as sns
sns.set_palette('bright')
def mark_points(im, df, file_name):
# this code put scatter plot on the image and saves the the figure
dpi = 100
height, width, nbands = im.shape
# What size does the figure need to be in inches to fit the image?
fig_size = width / float(dpi), height / float(dpi)
# Create a figure of the right size with one axes that takes up the full figure
fig = plt.figure(figsize=fig_size)
ax = fig.add_axes([0, 0, 1, 1])
# Hide spines, ticks, etc.
ax.axis('off')
# Display the image.
ax.imshow(im, interpolation='nearest')
sns.scatterplot(x='X',
y='Y',
data=df,
hue='Class',
ax=ax,
s=2,
edgecolor=None,
legend=False)
ax.set(xlim=[0, width], ylim=[height, 0], aspect=1)
# save image with cell annotation
fig.savefig(file_name, dpi=dpi, transparent=True)
# plt.close(fig)
plt.figure().clear()
plt.clf()
plt.close()
def annotate_images(output_dir,
process_num):
# create an image and random X and Y location for annotation
os.makedirs(output_dir, exist_ok=True)
for j in range(10000):
# this approximately the size of image I am processing
im_height, im_width = 3000, 3000
# print('{}'.format(process_num))
file_name = 'my_file_name_{}.jpg'.format(process_num)
output_file = os.path.join(output_dir, file_name)
# generate dataframe with data to plot
df = pd.DataFrame(columns=['X', 'Y', 'Class'])
num_points = 20000
df['X'] = np.random.randint(0, im_width, size=(num_points), dtype='int32').tolist()
df['Y'] = np.random.randint(0, im_height, size=(num_points), dtype='int32').tolist()
classes_ = ['A', 'B', 'C']
df['Class'] = [classes_[np.random.randint(0, 3)] for _ in range(num_points)]
# generate a random image
im = np.random.randint(low=0, high=255, size=(im_height, im_width, 3), dtype=np.uint8)
mark_points(im=im, df=df, file_name=output_file)
def run(output_dir,
num_processes=1,
multi_process=False
):
# number of folders
n = 100
for i in range(n):
if multi_process is True:
processes = [
mp.Process(target=annotate_images, args=(output_dir, process_num)) for process_num in range(num_processes)]
print('{} processes created'.format(num_processes))
# Run processes
for p in processes:
p.start()
# Exit the completed processes
for p in processes:
p.join()
print('All Processes finished!!!')
else:
annotate_images(output_dir=output_dir,
process_num=0
)
if __name__ == '__main__':
num_processes = 4
multi_process = True
home_dir = r'Output'
for i in range(3):
params = dict(output_dir=home_dir,
num_processes=num_processes,
multi_process=multi_process)
run(**params)
'''
Error message
image_annotate_cells.py:44: RuntimeWarning: More than 20 figures have been opened. Figures created through the pyplot interface (`matplotlib.pyplot.figure`) are retained until explicitly closed and may consume too much memory. (To control this warning, see the rcParam `figure.max_open_warning`).
plt.figure().clear()
image_annotate_cells.py:22: RuntimeWarning: More than 20 figures have been opened. Figures created through the pyplot interface (`matplotlib.pyplot.figure`) are retained until explicitly closed and may consume too much memory. (To control this warning, see the rcParam `figure.max_open_warning`).
fig = plt.figure(figsize=fig_size)
Process Process-1:
Traceback (most recent call last):
File "/home/DMP/DUDMP/COPAINGE/yhagos/.conda/envs/tf2cpu/lib/python3.6/multiprocessing/process.py", line 258, in _bootstrap
self.run()
File "/home/DMP/DUDMP/COPAINGE/yhagos/.conda/envs/tf2cpu/lib/python3.6/multiprocessing/process.py", line 93, in run
self._target(*self._args, **self._kwargs)
File "image_annotate_cells.py", line 74, in annotate_images
mark_points(im=im, df=df, file_name=output_file)
File "image_annotate_cells.py", line 42, in mark_points
fig.savefig(file_name, dpi=dpi, transparent=True)
File "/home/DMP/DUDMP/COPAINGE/yhagos/.conda/envs/tf2cpu/lib/python3.6/site-packages/matplotlib/figure.py", line 2203, in savefig
self.canvas.print_figure(fname, **kwargs)
File "/home/DMP/DUDMP/COPAINGE/yhagos/.conda/envs/tf2cpu/lib/python3.6/site-packages/matplotlib/backend_bases.py", line 2126, in print_figure
**kwargs)
File "/home/DMP/DUDMP/COPAINGE/yhagos/.conda/envs/tf2cpu/lib/python3.6/site-packages/matplotlib/cbook/deprecation.py", line 358, in wrapper
return func(*args, **kwargs)
File "/home/DMP/DUDMP/COPAINGE/yhagos/.conda/envs/tf2cpu/lib/python3.6/site-packages/matplotlib/backends/backend_agg.py", line 584, in print_jpg
FigureCanvasAgg.draw(self)
File "/home/DMP/DUDMP/COPAINGE/yhagos/.conda/envs/tf2cpu/lib/python3.6/site-packages/matplotlib/backends/backend_agg.py", line 393, in draw
self.figure.draw(self.renderer)
File "/home/DMP/DUDMP/COPAINGE/yhagos/.conda/envs/tf2cpu/lib/python3.6/site-packages/matplotlib/artist.py", line 38, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File "/home/DMP/DUDMP/COPAINGE/yhagos/.conda/envs/tf2cpu/lib/python3.6/site-packages/matplotlib/figure.py", line 1736, in draw
renderer, self, artists, self.suppressComposite)
File "/home/DMP/DUDMP/COPAINGE/yhagos/.conda/envs/tf2cpu/lib/python3.6/site-packages/matplotlib/image.py", line 137, in _draw_list_compositing_images
a.draw(renderer)
File "/home/DMP/DUDMP/COPAINGE/yhagos/.conda/envs/tf2cpu/lib/python3.6/site-packages/matplotlib/artist.py", line 38, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File "/home/DMP/DUDMP/COPAINGE/yhagos/.conda/envs/tf2cpu/lib/python3.6/site-packages/matplotlib/axes/_base.py", line 2630, in draw
mimage._draw_list_compositing_images(renderer, self, artists)
File "/home/DMP/DUDMP/COPAINGE/yhagos/.conda/envs/tf2cpu/lib/python3.6/site-packages/matplotlib/image.py", line 137, in _draw_list_compositing_images
a.draw(renderer)
File "/home/DMP/DUDMP/COPAINGE/yhagos/.conda/envs/tf2cpu/lib/python3.6/site-packages/matplotlib/artist.py", line 38, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File "/home/DMP/DUDMP/COPAINGE/yhagos/.conda/envs/tf2cpu/lib/python3.6/site-packages/matplotlib/collections.py", line 894, in draw
Collection.draw(self, renderer)
File "/home/DMP/DUDMP/COPAINGE/yhagos/.conda/envs/tf2cpu/lib/python3.6/site-packages/matplotlib/artist.py", line 38, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File "/home/DMP/DUDMP/COPAINGE/yhagos/.conda/envs/tf2cpu/lib/python3.6/site-packages/matplotlib/collections.py", line 369, in draw
self._offset_position)
File "/home/DMP/DUDMP/COPAINGE/yhagos/.conda/envs/tf2cpu/lib/python3.6/site-packages/matplotlib/path.py", line 197, in vertices
#property
KeyboardInterrupt
Traceback (most recent call last):
File "image_annotate_cells.py", line 124, in <module>
run(**params)
File "image_annotate_cells.py", line 97, in run
p.join()
File "/home/DMP/DUDMP/COPAINGE/yhagos/.conda/envs/tf2cpu/lib/python3.6/multiprocessing/process.py", line 124, in join
res = self._popen.wait(timeout)
File "/home/DMP/DUDMP/COPAINGE/yhagos/.conda/envs/tf2cpu/lib/python3.6/multiprocessing/popen_fork.py", line 50, in wait
return self.poll(os.WNOHANG if timeout == 0.0 else 0)
File "/home/DMP/DUDMP/COPAINGE/yhagos/.conda/envs/tf2cpu/lib/python3.6/multiprocessing/popen_fork.py", line 28, in poll
pid, sts = os.waitpid(self.pid, flag)
KeyboardInterrupt
Related
I have the following sample code:
import glob
import random
import tensorflow as tf
import cv2
def random_blur(image):
# do stuff which can't be done with a tf.image function...
random_x_blur = random.randint(1, 3)
random_y_blur = random.randint(1, 3)
return cv2.blur(image, (random_x_blur, random_y_blur))
def transform(image):
image = tf.image.random_jpeg_quality(image, 75, 100)
image = tf.image.random_brightness(image, 0.5)
image = tf.image.random_contrast(image, 0.2, 0.5)
# here's the problem...
# image = tf.py_function(func=random_blur, inp=[image], Tout=tf.uint8)
return image
def process_path(file_path):
image = tf.io.read_file(file_path)
image = tf.image.decode_png(image, channels=1)
return transform(image), image
train_directory = 'data/small/'
train_files = glob.glob(train_directory + '*.png')
ds_train = tf.data.Dataset.from_tensor_slices(train_files)
boundaries = [100, 200, 300, 400]
batch_sizes = [16, 16, 16, 16, 16]
ds_train = ds_train.map(process_path, 4)
ds_train = ds_train.bucket_by_sequence_length(element_length_func=lambda x, y: tf.shape(x)[1],
bucket_boundaries=boundaries,
bucket_batch_sizes=batch_sizes)
I'm trying to create a Tensorflow Dataset from variable-width 60px-high images in a directory, using the bucket_by_sequence_length() function to ensure the images in each minibatch have the same dimensions. This all works fine until I uncomment the line beneath "here's the problem" in the code above. When you uncomment that and run it, it produces the following error:
Traceback (most recent call last):
File "test.py", line 34, in <module>
ds_train = ds_train.bucket_by_sequence_length(element_length_func=lambda x, y: tf.shape(x)[1],
File "/Users/garnet/Library/Python/3.8/lib/python/site-packages/tensorflow/python/data/ops/dataset_ops.py", line 3120, in bucket_by_sequence_length
return self.group_by_window(
File "/Users/garnet/Library/Python/3.8/lib/python/site-packages/tensorflow/python/data/ops/dataset_ops.py", line 2976, in group_by_window
return _GroupByWindowDataset(
File "/Users/garnet/Library/Python/3.8/lib/python/site-packages/tensorflow/python/data/ops/dataset_ops.py", line 5841, in __init__
self._make_reduce_func(reduce_func, input_dataset)
File "/Users/garnet/Library/Python/3.8/lib/python/site-packages/tensorflow/python/data/ops/dataset_ops.py", line 5890, in _make_reduce_func
self._reduce_func = structured_function.StructuredFunctionWrapper(
File "/Users/garnet/Library/Python/3.8/lib/python/site-packages/tensorflow/python/data/ops/structured_function.py", line 271, in __init__
self._function = fn_factory()
File "/Users/garnet/Library/Python/3.8/lib/python/site-packages/tensorflow/python/eager/function.py", line 2610, in get_concrete_function
graph_function = self._get_concrete_function_garbage_collected(
File "/Users/garnet/Library/Python/3.8/lib/python/site-packages/tensorflow/python/eager/function.py", line 2576, in _get_concrete_function_garbage_collected
graph_function, _ = self._maybe_define_function(args, kwargs)
File "/Users/garnet/Library/Python/3.8/lib/python/site-packages/tensorflow/python/eager/function.py", line 2760, in _maybe_define_function
graph_function = self._create_graph_function(args, kwargs)
File "/Users/garnet/Library/Python/3.8/lib/python/site-packages/tensorflow/python/eager/function.py", line 2670, in _create_graph_function
func_graph_module.func_graph_from_py_func(
File "/Users/garnet/Library/Python/3.8/lib/python/site-packages/tensorflow/python/framework/func_graph.py", line 1247, in func_graph_from_py_func
func_outputs = python_func(*func_args, **func_kwargs)
File "/Users/garnet/Library/Python/3.8/lib/python/site-packages/tensorflow/python/data/ops/structured_function.py", line 248, in wrapped_fn
ret = wrapper_helper(*args)
File "/Users/garnet/Library/Python/3.8/lib/python/site-packages/tensorflow/python/data/ops/structured_function.py", line 177, in wrapper_helper
ret = autograph.tf_convert(self._func, ag_ctx)(*nested_args)
File "/Users/garnet/Library/Python/3.8/lib/python/site-packages/tensorflow/python/autograph/impl/api.py", line 689, in wrapper
return converted_call(f, args, kwargs, options=options)
File "/Users/garnet/Library/Python/3.8/lib/python/site-packages/tensorflow/python/autograph/impl/api.py", line 377, in converted_call
return _call_unconverted(f, args, kwargs, options)
File "/Users/garnet/Library/Python/3.8/lib/python/site-packages/tensorflow/python/autograph/impl/api.py", line 458, in _call_unconverted
return f(*args, **kwargs)
File "/Users/garnet/Library/Python/3.8/lib/python/site-packages/tensorflow/python/data/ops/dataset_ops.py", line 3111, in batching_fn
shapes = make_padded_shapes(
File "/Users/garnet/Library/Python/3.8/lib/python/site-packages/tensorflow/python/data/ops/dataset_ops.py", line 3083, in make_padded_shapes
shape = [
File "/Users/garnet/Library/Python/3.8/lib/python/site-packages/tensorflow/python/framework/tensor_shape.py", line 882, in __iter__
raise ValueError("Cannot iterate over a shape with unknown rank.")
ValueError: Cannot iterate over a shape with unknown rank.
Likewise, my code works fine if I uncomment that line but remove the call to bucket_by_sequence_length() and limit my training data to images with identical dimensions.
It seems that bucket_by_sequence_length() and tf.py_function() don't play nice together, even with eager mode enabled. I need to do some image augmentations/transformations which the standard tf.image functions don't provide. Any ideas?
I am running the following command in spyder,
import matplotlib.pyplot as plt
fig, axs = plt.subplots(2, 2)
Traceback (most recent call last):
File "/home/hh/.local/lib/python3.8/site-packages/matplotlib_inline/backend_inline.py", line 41, in show
display(
File "/home/hh/anaconda3/envs/gee/lib/python3.8/site-packages/IPython/core/display.py", line 327, in display
publish_display_data(data=format_dict, metadata=md_dict, **kwargs)
File "/home/hh/anaconda3/envs/gee/lib/python3.8/site-packages/IPython/core/display.py", line 119, in publish_display_data
display_pub.publish(
File "/home/hh/.local/lib/python3.8/site-packages/ipykernel/zmqshell.py", line 138, in publish
self.session.send(
File "/home/hh/anaconda3/envs/gee/lib/python3.8/site-packages/jupyter_client/session.py", line 830, in send
to_send = self.serialize(msg, ident)
File "/home/hh/anaconda3/envs/gee/lib/python3.8/site-packages/jupyter_client/session.py", line 704, in serialize
content = self.pack(content)
File "/home/hh/anaconda3/envs/gee/lib/python3.8/site-packages/jupyter_client/session.py", line 95, in json_packer
return jsonapi.dumps(
File "/home/hh/anaconda3/envs/gee/lib/python3.8/site-packages/zmq/utils/jsonapi.py", line 40, in dumps
s = jsonmod.dumps(o, **kwargs)
File "/home/hh/anaconda3/envs/gee/lib/python3.8/site-packages/simplejson/init.py", line 398, in dumps
return cls(
File "/home/hh/anaconda3/envs/gee/lib/python3.8/site-packages/simplejson/encoder.py", line 296, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/home/hh/anaconda3/envs/gee/lib/python3.8/site-packages/simplejson/encoder.py", line 378, in iterencode
return _iterencode(o, 0)
File "/home/hh/anaconda3/envs/gee/lib/python3.8/site-packages/simplejson/encoder.py", line 44, in encode_basestring
s = str(s, 'utf-8')
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte
Got the same error if I run the same code in jupyter lab. However, if I run the command on terminal, the fig, ax = plt.subplots() works fine.
This only happens recently and I didn't have this issue before. Checked online material, but didn't find a solution. appreciate if only can provide any insights. thanks.
I had the same problem running plain jupyter and within vscode.
Try updating the jupyter installation incl. required libraries. In my case
pip3 install --upgrade jupyter_client pyzmq
fixed the problem.
I have a pandas dataframe raw_data with two columns: 'T' and 'BP':
T BP
0 -0.500 115.790
1 -0.499 115.441
2 -0.498 115.441
3 -0.497 115.441
4 -0.496 115.790
... ... ...
647163 646.663 105.675
647164 646.664 105.327
647165 646.665 105.327
647166 646.666 105.327
647167 646.667 104.978
[647168 rows x 2 columns]
I want to apply the Hodges-Lehmann mean (it's a robust average) over a rolling window and create a new column. Here's the function:
def hodgesLehmannMean(x):
m = np.add.outer(x, x)
ind = np.tril_indices(len(x), 0)
return 0.5 * np.median(m[ind])
I therefore write:
raw_data[new_col] = raw_data['BP'].rolling(21, min_periods=1, center=True,
win_type=None, axis=0, closed=None).agg(hodgesLehmannMean)
but I get a string of error messages:
Traceback (most recent call last):
File "C:\Users\tkpme\miniconda3\lib\runpy.py", line 194, in _run_module_as_main
return _run_code(code, main_globals, None,
File "C:\Users\tkpme\miniconda3\lib\runpy.py", line 87, in _run_code
exec(code, run_globals)
File "c:\Users\tkpme\.vscode\extensions\ms-python.python-2020.8.101144\pythonFiles\lib\python\debugpy\__main__.py", line 45, in <module>
cli.main()
File "c:\Users\tkpme\.vscode\extensions\ms-python.python-2020.8.101144\pythonFiles\lib\python\debugpy/..\debugpy\server\cli.py", line 430, in main
run()
File "c:\Users\tkpme\.vscode\extensions\ms-python.python-2020.8.101144\pythonFiles\lib\python\debugpy/..\debugpy\server\cli.py", line 267, in run_file
runpy.run_path(options.target, run_name=compat.force_str("__main__"))
File "C:\Users\tkpme\miniconda3\lib\runpy.py", line 265, in run_path
return _run_module_code(code, init_globals, run_name,
File "C:\Users\tkpme\miniconda3\lib\runpy.py", line 97, in _run_module_code
_run_code(code, mod_globals, init_globals,
File "C:\Users\tkpme\miniconda3\lib\runpy.py", line 87, in _run_code
exec(code, run_globals)
File "c:\Users\tkpme\OneDrive\Documents\Work\CMC\BP Satya and Suresh\Code\Naveen_peak_detect test.py", line 227, in <module>
main()
File "c:\Users\tkpme\OneDrive\Documents\Work\CMC\BP Satya and Suresh\Code\Naveen_peak_detect test.py", line 75, in main
raw_data[new_col] = raw_data['BP'].rolling(FILTER_WINDOW, min_periods=1, center=True, win_type=None,
File "C:\Users\tkpme\miniconda3\lib\site-packages\pandas\core\window\rolling.py", line 1961, in aggregate
return super().aggregate(func, *args, **kwargs)
File "C:\Users\tkpme\miniconda3\lib\site-packages\pandas\core\window\rolling.py", line 523, in aggregate
return self.apply(func, raw=False, args=args, kwargs=kwargs)
File "C:\Users\tkpme\miniconda3\lib\site-packages\pandas\core\window\rolling.py", line 1987, in apply
return super().apply(
File "C:\Users\tkpme\miniconda3\lib\site-packages\pandas\core\window\rolling.py", line 1300, in apply
return self._apply(
File "C:\Users\tkpme\miniconda3\lib\site-packages\pandas\core\window\rolling.py", line 507, in _apply
result = calc(values)
File "C:\Users\tkpme\miniconda3\lib\site-packages\pandas\core\window\rolling.py", line 495, in calc
return func(x, start, end, min_periods)
File "C:\Users\tkpme\miniconda3\lib\site-packages\pandas\core\window\rolling.py", line 1326, in apply_func
return window_func(values, begin, end, min_periods)
File "pandas\_libs\window\aggregations.pyx", line 1375, in pandas._libs.window.aggregations.roll_generic_fixed
File "c:\Users\tkpme\OneDrive\Documents\Work\CMC\BP Satya and Suresh\Code\Naveen_peak_detect test.py", line 222, in hodgesLehmannMean
m = np.add.outer(x, x)
File "C:\Users\tkpme\miniconda3\lib\site-packages\pandas\core\series.py", line 705, in __array_ufunc__
return construct_return(result)
File "C:\Users\tkpme\miniconda3\lib\site-packages\pandas\core\series.py", line 694, in construct_return
raise NotImplementedError
NotImplementedError
which appear to be driven by the line
m = np.add.outer(x, x)
and points to something not being implemented or numpy being missing. But I import numpy right at the beginning as follows:
import numpy as np
import pandas as pd
The function works perfectly well on its own if I feed it a list or a numpy array, so I'm not sure what the problem is. Interestingly, if I use the median instead of the Hodges-Lehmann Mean, it runs like a charm
raw_data[new_col] = raw_data['BP'].rolling(21, min_periods=1, center=True,
win_type=None, axis=0, closed=None).median()
What is the cause of my problem, and how do I fix it?
Sincerely
Thomas Philips
I've tried your code with a small dataframe and it worked well, so maybe there is something on your dataframe that must be cleaned or transformed.
Solved it. It turns out that
m = np.add.outer(x, x)
requires x to be array like. When I tested it using lists, numpy arrays, etc. it worked perfectly, just as it did for you. But the .rolling line generates a slice of a dataframe, which is not array like, and the function fails with a confusing error message. I modified the function to create a numpy array from the input and it now works as it should.
def hodgesLehmannMean(x):
x_array = np.array(x)
m = np.add.outer(x_array, x_array)
ind = np.tril_indices(len(x_array), 0)
return 0.5 * np.median(m[ind])
Thanks for looking at it!
My dataframe consists of 59 columns with +2000 rows of data (data collected per second). I need to sum/add all data in individual columns 29 to 60, to give 31 bin totals. I then need to plot the 31 bin totals in a histogram with bin number as the x axis and number of counts on the y axis.
NB: I am working in a Function inside a Class called from elsewhere.
I have summed/added each specified column using the sum() function. The histogram function is then called, and it gets as far as producing an empty figure and then produces a long list of errors, culminating at a datetime error (I am not sure how datetime is involved in this...). Please can someone point me in the right direction and help get my histogram working?
The examples shows the preceding code and just the first 5 bins.
import pandas as pd
import datetime as dt
import matplotlib.pyplot as plt
class Pops(object):
def __init__(self, popsfile): #, pops_hdr_lines):
'''
...
'''
#________________________________________________
# # READ IN FILES AND CONCATENATE FILES
if not isinstance(popsfile, list):
self.POPSfile = [popsfile]
else:
self.POPSfile = popsfile
# read in multiple POPS datafiles into a list
dfs = []
for file in self.POPSfile:
df = pd.read_csv(file, sep=',', header=0) # PANDAS!
dfs.append(df)
# concatenate all dataframes together
data = pd.concat(dfs)
# ------------------------------------------------------------
# create new time stamp
# determine date
date_string = self.POPSfile[0][-16:-8] # extracts YYYYMMDD.
popsdate = dt.datetime.strptime(date_string, '%Y%m%d')
# Convert from date and time in sam since 1/1/1970
data.DateTime = pd.to_datetime(data.DateTime, errors='coerce', unit='s')
# Rename columns to remove whitespaces
data = data.rename(columns={' Status': 'Status', ' PartCt': 'PartCt', ' PartCon': 'PartCon',' BL': 'BL',
' P': 'P', ' POPS_Flow': 'POPS_Flow', ' LDTemp': 'LDTemp', ' Temp': 'Temp',
' Laser_Current': 'Laser_Current'})
self.data = data
def plot_housekeeping(self, path, show_save):
'''plot some of the basic data
'''
# histogram attempt
bins = self.data[['b0', 'b1', 'b2', 'b3', 'b4']].sum() # sums the bins of interest
print(bins) # check output
plt.hist(bins)
plt.show()
return None
if __name__ == '__main__':
main()
This is what I get:
b0 12965454
b1 9168956
b2 4178861
b3 2878718
b4 2699768
dtype: int64
Traceback (most recent call last):
File "/opt/scitools/environments/default/current/lib/python3.6/site-packages/matplotlib/backends/backend_qt5.py", line 519, in _draw_idle
self.draw()
File "/opt/scitools/environments/default/current/lib/python3.6/site-packages/matplotlib/backends/backend_agg.py", line 437, in draw
self.figure.draw(self.renderer)
File "/opt/scitools/environments/default/current/lib/python3.6/site-packages/matplotlib/artist.py", line 55, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File "/opt/scitools/environments/default/current/lib/python3.6/site-packages/matplotlib/figure.py", line 1493, in draw
renderer, self, artists, self.suppressComposite)
File "/opt/scitools/environments/default/current/lib/python3.6/site-packages/matplotlib/image.py", line 141, in _draw_list_compositing_images
a.draw(renderer)
File "/opt/scitools/environments/default/current/lib/python3.6/site-packages/matplotlib/artist.py", line 55, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File "/opt/scitools/environments/default/current/lib/python3.6/site-packages/matplotlib/axes/_base.py", line 2635, in draw
mimage._draw_list_compositing_images(renderer, self, artists)
File "/opt/scitools/environments/default/current/lib/python3.6/site-packages/matplotlib/image.py", line 141, in _draw_list_compositing_images
a.draw(renderer)
File "/opt/scitools/environments/default/current/lib/python3.6/site-packages/matplotlib/artist.py", line 55, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File "/opt/scitools/environments/default/current/lib/python3.6/site-packages/matplotlib/axis.py", line 1190, in draw
ticks_to_draw = self._update_ticks(renderer)
File "/opt/scitools/environments/default/current/lib/python3.6/site-packages/matplotlib/axis.py", line 1028, in _update_ticks
tick_tups = list(self.iter_ticks()) # iter_ticks calls the locator
File "/opt/scitools/environments/default/current/lib/python3.6/site-packages/matplotlib/axis.py", line 971, in iter_ticks
majorLocs = self.major.locator()
File "/opt/scitools/environments/default/current/lib/python3.6/site-packages/matplotlib/dates.py", line 1249, in __call__
self.refresh()
File "/opt/scitools/environments/default/current/lib/python3.6/site-packages/matplotlib/dates.py", line 1269, in refresh
dmin, dmax = self.viewlim_to_dt()
File "/opt/scitools/environments/default/current/lib/python3.6/site-packages/matplotlib/dates.py", line 1027, in viewlim_to_dt
return num2date(vmin, self.tz), num2date(vmax, self.tz)
File "/opt/scitools/environments/default/current/lib/python3.6/site-packages/matplotlib/dates.py", line 522, in num2date
return _from_ordinalf(x, tz)
File "/opt/scitools/environments/default/current/lib/python3.6/site-packages/matplotlib/dates.py", line 322, in _from_ordinalf
dt = datetime.datetime.fromordinal(ix).replace(tzinfo=UTC)
ValueError: year 37173 is out of range
When I try running the very simple code snippet from www.matplotlib.org,
from matplotlib import rc
rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
## for Palatino and other serif fonts use:
#rc('font',**{'family':'serif','serif':['Palatino']})
rc('text', usetex=True)
import numpy as np
import matplotlib.pyplot as plt
# Example data
t = np.arange(0.0, 1.0 + 0.01, 0.01)
s = np.cos(4 * np.pi * t) + 2
plt.rc('text', usetex=True)
plt.rc('font', family='serif')
plt.plot(t, s)
plt.xlabel(r'\textbf{time} (s)')
plt.ylabel(r'\textit{voltage} (mV)',fontsize=16)
plt.title(r"\TeX\ is Number "
r"$\displaystyle\sum_{n=1}^\infty\frac{-e^{i\pi}}{2^n}$!",
fontsize=16, color='gray')
# Make room for the ridiculously large title.
plt.subplots_adjust(top=0.8)
plt.savefig('tex_demo')
plt.show()
This is highly unusual this code has worked for me before and I cannot figure out what the issue is. The error message that I receive is enormous and shown below. Does anybody know what the issue might be?
Thanks!!
Traceback (most recent call last):
File
"/Users/evan/anaconda3/lib/python3.6/site-packages/IPython/core/formatters.py",
line 332, in call
return printer(obj)
File
"/Users/evan/anaconda3/lib/python3.6/site-packages/IPython/core/pylabtools.py",
line 237, in
png_formatter.for_type(Figure, lambda fig: print_figure(fig, 'png', **kwargs))
File
"/Users/evan/anaconda3/lib/python3.6/site-packages/IPython/core/pylabtools.py",
line 121, in print_figure
fig.canvas.print_figure(bytes_io, **kw)
File
"/Users/evan/anaconda3/lib/python3.6/site-packages/matplotlib/backend_bases.py",
line 2216, in print_figure
**kwargs)
File
"/Users/evan/anaconda3/lib/python3.6/site-packages/matplotlib/backends/backend_agg.py",
line 507, in print_png
FigureCanvasAgg.draw(self)
File
"/Users/evan/anaconda3/lib/python3.6/site-packages/matplotlib/backends/backend_agg.py",
line 430, in draw
self.figure.draw(self.renderer)
File
"/Users/evan/anaconda3/lib/python3.6/site-packages/matplotlib/artist.py",
line 55, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File
"/Users/evan/anaconda3/lib/python3.6/site-packages/matplotlib/figure.py",
line 1299, in draw
renderer, self, artists, self.suppressComposite)
File
"/Users/evan/anaconda3/lib/python3.6/site-packages/matplotlib/image.py",
line 138, in _draw_list_compositing_images
a.draw(renderer)
File
"/Users/evan/anaconda3/lib/python3.6/site-packages/matplotlib/artist.py",
line 55, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File
"/Users/evan/anaconda3/lib/python3.6/site-packages/matplotlib/axes/_base.py",
line 2437, in draw
mimage._draw_list_compositing_images(renderer, self, artists)
File
"/Users/evan/anaconda3/lib/python3.6/site-packages/matplotlib/image.py",
line 138, in _draw_list_compositing_images
a.draw(renderer)
File
"/Users/evan/anaconda3/lib/python3.6/site-packages/matplotlib/artist.py",
line 55, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File
"/Users/evan/anaconda3/lib/python3.6/site-packages/matplotlib/axis.py",
line 1135, in draw
renderer)
File
"/Users/evan/anaconda3/lib/python3.6/site-packages/matplotlib/axis.py",
line 1075, in _get_tick_bboxes
extent = tick.label1.get_window_extent(renderer)
File
"/Users/evan/anaconda3/lib/python3.6/site-packages/matplotlib/text.py",
line 933, in get_window_extent
bbox, info, descent = self._get_layout(self._renderer)
File
"/Users/evan/anaconda3/lib/python3.6/site-packages/matplotlib/text.py",
line 308, in _get_layout
ismath=False)
File
"/Users/evan/anaconda3/lib/python3.6/site-packages/matplotlib/backends/backend_agg.py",
line 226, in get_text_width_height_descent
s, fontsize, renderer=self)
File
"/Users/evan/anaconda3/lib/python3.6/site-packages/matplotlib/texmanager.py",
line 602, in get_text_width_height_descent
dvifile = self.make_dvi(tex, fontsize)
File
"/Users/evan/anaconda3/lib/python3.6/site-packages/matplotlib/texmanager.py",
line 393, in make_dvi
stderr=subprocess.STDOUT)
File "/Users/evan/anaconda3/lib/python3.6/subprocess.py", line 336,
in check_output
**kwargs).stdout
File "/Users/evan/anaconda3/lib/python3.6/subprocess.py", line 403,
in run
with Popen(*popenargs, **kwargs) as process:
File "/Users/evan/anaconda3/lib/python3.6/subprocess.py", line 709,
in init
restore_signals, start_new_session)
File "/Users/evan/anaconda3/lib/python3.6/subprocess.py", line 1344,
in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'latex':
'latex'
For linux:
sudo yum install latex
sudo yum install dvipng
For Window:
install texlive.
ref. https://matplotlib.org/tutorials/text/usetex.html?highlight=latex
Download miktex and add the path in environment variables for Windows.