Issue with importing data into csv file for matplotlib graph - python

I'm fairly new to data analysis with matplotlib and I was hoping I could get some guidance as to where I'm going wrong. As part of a personal project, I've made a face mask detection system using a raspberry pi following the tutorial on https://www.tomshardware.com/how-to/raspberry-pi-face-mask-detector . This part works great, however I was hoping to take it a step further by using the data it produces to form a graph of mask adherence over a period of time
In my attempt I created 2 variables, "mask_off" and "mask_on". When a person is detected wearing a mask or not, the corresponding value increases by 1. From here I was hoping to write these variables to a csv file and plot a graph from there using the values. The code I've written below doesn't seem to run at all:
from time import sleep, strftime, time
import matplotlib.pyplot as plt
import numpy as np
with open('home/pi/face_mask_detection/mask_adherence.csv', 'a') as log:
while True:
nwm = mask_off
wm = mask_on
y.append(mask_off)
x.append(mask_on)
plt.clf()
plt.scatter(x, y)
plt.plot(x,y)
log.write('{0},{1}\n'.format(strftime('%Y-%m-%d %H:%M:%S'),str(nwm)))
log.write('{0},{1}\n'.format(strftime('%Y-%m-%d %H:%M:%S'),str(wm)))
plt.pause(1)
plt.draw()
When I run the code I only get "Import Error: numpy.core.multiarray failed to import" so I can't even test if the code actually works. Chances are I'm taking the complete wrong approach to this so any kind of guidance, advice or tips would be greatly appreciated. Thanks.

Related

Jupyter and %matplotlib inline lost axis

I am having a really weird issue with using the %matplotlib inline code in my jupyter notebook for plotting graphs using both pyplot and the pandas plotting function.
The problem is they show up without any axes, and basically just show the graph area without anything aside from data points.
I found adding:
import matplotlib as mpl
mpl.rcParams.update(mpl.rcParamsDefault)
reverse it, but I find it odd that should do that every time as the effect disappears as soon as I run %matplotlib inlinecommand.
an example could be
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
plt.scatter(A,A)
plt.tight_layout()
plt.xlabel('here')
plt.show()
This would generate the graph below:
Weird enough if I uses the savefig it get plotted with the axis, if I uses the right-click -> new output -> save as figure, I also get the graph with the figures !!
like this:
Can anyone help me understand what is wrong, which global setting did I mess up, and how do I revert it?
(I don't remember messing around with any settings aside from some settings for pandas, but don't think they should have had an impact)
as mentioned running mpl.rcParams.update(mpl.rcParamsDefault) command does bring it back to normal until I run %matplotlib inline` again !!
Any help would be much appreciated.
Okay I am sorry I think I can answer the question myself now.
With the helpfull #Mr. T asking for the imgur link made me realize what was going on. I had starting using the dark jupyter lab theme, and the graph would generate plots with transparent background, ie. the text and lines where there, but I just couldn't see them.
The trick is to change the background color preferably globally, but that will be a task for tomorrow.

Why it shows "NameError: name 'histogram' is not defined"?

I'm taking a course on Coursera and doing an assignment after watching a teaching video.
I wanna know why it shows "NameError: name 'histogram' is not defined" after running my own code.
Add histogram library in your code. please add line in the starting of the code. I should work properly.
from histograms import histograms
You'll need to import the Histogram function as it is not built into Python. There are a few different packages that offer histograms -- for example pyplot and numpy. Here's an example using numpy
import numpy as np
np.histogram([1, 2])
Documentation: https://numpy.org/doc/1.18/reference/generated/numpy.histogram.html

Incorrect backend configuration with macosx in (old) matplotlib: plt.ion different from savefig, here overwritten alpha keyword

I am using interactive python with plt.ion() for generating figures (v2.7) and have noticed that the figure looks different from the figure exported by savefig (this is not a DPI issue (cf. matplotlib savefig() plots different from show()) - I think it might be a backend issue, but would appreciate help as I don't understand this properly).
Specifically, I wanted visualise the importance of a series of points by the intensity of their colour, which I thought I could do with the "alpha" keyword in matplotlib.
When I just do this, this works fine,
but when I want to add a line to the figure, the alpha keyword seemed to not work any more, and plt.ion() shows this:
I initially thought that perhaps the following issue on github may be related:
https://github.com/matplotlib/matplotlib/issues/4580
but then I noticed that exporting the figure actually produced the following file (i.e. as desired):
It would be great to understand a bit better what is going on, and how I can avoid such issues in the future. Is plt.ion()/plt.show() not the best way to show figures in interactive python, or is this an issue with the alpha keyword?
The code is here:
import numpy as np
from numpy import random as random
from matplotlib import pyplot as plt
fig2,ax2=plt.subplots(1,1,figsize=(3,3),sharey=True)
for ii in range(1):
ax2.plot(np.linspace(0,200,200), [0.1]*200, c= 'k')
for i in range(200):
test2=random.randint(5)
ydata= random.rand(test2)
test = random.rand(test2)
for j in range(test2):
ax2.plot(i,ydata[j],'o',ms=4, c= 'Darkblue',alpha=test[j],markeredgecolor='None')

plt.show() not showing data instead holding it for next plot (spyder)

I have been using the same setup for quite some time now but suddenly I am no longer allowed to plot more than one graph in a program.
Usually I can plot multiple plots after each other and let the program run through it. It executes the next lines of code after closing the first window. However, recently the first plot is not shown but instead the data is added to the last plot.
I have included a sample code which used to give me two plots but now only one.
import matplotlib.pyplot as plt
import numpy as np
random_num = np.random.randint(0,5,10)
random_num_2 = np.random.randint(0,100,10)
plt.plot(random_num, 'ko')
plt.show()
plt.plot(random_num_2, 'g*')
plt.show()
The first image shows the output from my program. But I would like to have them separated into two plots like Figure 2 and 3 show.
Maybe I should add that I am using Python 3.6 with Spyder 3.2.4. The graphics option is set to display it in Qt5 even though I tried all settings and only 'Inline' shows me the results the way I want it.
Sorry if this is a very simple question. I have tried googling but I only come up with questions about my topic where the way mine works would be the solution not the problem.
#TheresaOtt. I would suggest you create a new figure instance (plt.figure()) for each plot and use only once at the end the plt.show() command.

Wrong dates in the index plotly with a second graph I did not ask for

I am trying to plot some graphs with plotly and, after several times having the wrong graph, i backed to the basics and tried to plot an example from the plotly web, but the same error appears:
My dates are not dates, but an extremely high number (10^18 order) and I get a second small graph that noone asked for.
import plotly.plotly as py
import plotly.graph_objs as go
import pandas_datareader as web
from datetime import datetime
import fix_yahoo_finance as yf
yf.pdr_override()
df = web.DataReader("aapl", 'robinhood').reset_index()
trace = go.Candlestick(x=df.Date,
open=df.Open,
high=df.High,
low=df.Low,
close=df.Close)
data = [trace]
py.plot(data, filename='simple_candlestick')
I just changed the source (morningstar is down) and used the offline version instead of the live program, but the error still appeared if I used the web anyways, so It does not matter.
EDIT:
After a previous edit, the images are no longer appearing in the post, sorry for the inconveniences.
OK, I managed to fix the date problem inserting the index with dates in an array and using that array as the x.
Also, I figured out that the second small graph only appears with the go.Candlestick representation (since it does not appear with figure_factory or go.Scatter hehe).
Thanks :)

Categories

Resources