matplotlib.pyplot.plot() doesn't show the graph - python

I am learning Python and I have a side project to learn to display data using matplotlib.pyplot module. Here is an example to display the data using dates[] and prices[] as data. Does anyone know why we need line 5 and line 6? I am confused why this step is needed to have the graph displayed.
from sklearn import linear_model
import matplotlib.pyplot as plt
def showgraph(dates, prices):
dates = numpy.reshape(dates, (len(dates), 1)) # line 5
prices = numpy.reshape(prices, (len(prices), 1)) # line 6
linear_mod = linear_model.LinearRegression()
linear_mod.fit(dates,prices)
plt.scatter(dates,prices,color='yellow')
plt.plot(dates,linear_mod.predict(dates),color='green')
plt.show()

try the following in terminal to check the backend:
import matplotlib
import matplotlib.pyplot
print matplotlib.backends.backend
If it shows 'agg', it is a non-interactive one and wont show but plt.savefig works.
To show the plot, you need to switch to TkAgg or Qt4Agg.
You need to edit the backend in matplotlibrc file. To print its location in terminal do the following.
import matplotlib
matplotlib.matplotlib_fname()
more about matplotlibrc

Line 5 and 6 transform what Im assuming are row vectors (im not sure how data and prices are encoded before this transformation) into column vectors. So now you have vectors that look like this.
[0,
1,
2,
3]
which is the form that linear_model.Linear_Regression.fit() is expecting. The reshaping was not necessary for plotting under the assumption that data and prices are row vectors.

My approach is exactly like yours but still without line 5 and 6 display is correct. I think those line are unnecessary. It seems that you do not need fit() function because of your input data are in row format.

Related

Displaying Matplotlib Line Graph in Jupyter

I'm working on taking some data from a dataset and plotting certain aspects of it. Here's my code below:
import matplotlib.pyplot as plt
df1 = pd.read_csv('dataset_1.csv')
soil_moisture = list(df1.Soil_Moisture)
soil_temperature = list(df1.Soil_Temp)
print(len(soil_moisture))
print(len(soil_temperature))
plt.plot([soil_moisture], [soil_temperature])
plt.show()
As you can see, it takes data from each of those columns and tries to make a line graph. However, when I run, it just displays an empty graph. This is weird since when I print the soil_moisture and soil_temperature, it tells me that there's actual data, and none of my other plots in the same notebook are experiencing this. All help is appreciated!
Here's an image of the jupyter output
Please revise line 7 of your code as:
plt.plot(soil_moisture, soil_temperature)
When you use [soil_moisture] that means you are generating another list with list soil_moisture as its first element.

How To Remove Extra Horizontal Line In Matplotlib Plot

I am plotting data from a .txt file using Matplotlib and although the plot looks as expected there is an odd horizontal line through the plot. This occurs across three different .txt data files I've tried. I plotted the data in Mathematica to ensure that it is not an artifact of the data. I am trying to remove the line from my data.
I've tried the accessing some of the Matplotlib methods like lines.remove() with no luck. Below is the code I'm executing and the resulting plot.
import numpy as np
import matplotlib.pyplot as plt
neon = np.loadtxt("data/neon.txt")
neon_plot = plt.plot(neon)
plt.grid()
This is an example of the horizontal line going through my plots

plotting/graphing excel file data using python

I'm new to Python and there is a piece of Python coding that I am having trouble getting to graph.
Specifically how to parse data from an Excel spreadsheet in order to generate and plot some basic value comparison graphs.
I'm using the Spyder IDE with Python 3.6.3.
The file 'foc' location is:
C:\Users\Murphy\Desktop\WinPython-64bit-3.6.3.0Qt5\PYWorkFiles\foc.csv
I have more than one version of the excel spreadsheet foc file as I have attempted to graph it in more than one format. The two formats it is stored in at present are csv and xlsx
The code scraps I have put together at present are:
import xlrd
workbook = xlrd.open_workbook('foc.xlsx')
from csv import reader
import matplotlib.pyplot as plt
with open('foc.csv', 'r') as f:
data = list(reader(f))
taste = [i[6] for i in data]
plt.plot(range(len(taste)), taste)
plt.show()
plt.plot()
All these pieces of code generate is two useless graphs (I've attached them below) with only the first one even showing any of the foc spreadsheet data.
Can I get any help with this? I have very little knowledge of how to use Python.
graph1
graph2
To make it as simple as possible, I recommend using numpy(pip install numpy to install it). Using numpy we can do this:
import matplotlib.pyplot as plt
import numpy as np
x, y = np.loadtxt('foc.csv', delimiter=',', unpack=True)
plt.plot(x,y, label='Loaded from file!')
plt.xlabel('x')
plt.ylabel('y')
plt.title('Test')
plt.legend()
plt.show()
and this is our result
foc.csv:
1, 10
2, 20
3, 30
4, 40
5, 50
If you still need more help or want to get into more complex things using matplotlib, I recommend checking out sentdex's tutorials

editing plot - python

Hi I have a code that plots 2D data from a .dat file (I'll call it filename.dat which is just a .dat file with 2 columns of numbers). It works fine, I just have some questions as to how to improve it.
How can I edit my code to make the axes label larger and add a title? This code is not so easy to edit the way I have it written now. I have tried adding the fontsize,title into the plotfile(...) command, but this did not work. Thanks for the help! My code is below.
import numpy as np
import matplotlib.pyplot as plt
#unpack file data
dat_file = np.loadtxt("filename.dat",unpack=True)
plt.plotfile('filename.dat', delimiter=' ',cols=(0,1), names=('x','y'),marker='0')
plt.show()
I assume you want to add them to the plot.
You can add a title with:
plt.title("MyTitle")
and you add text to the graph with
# the following coordinates need to be determined with experimentation
# put them at a location and move them around if they are in
# the way of the graph
x = 5
y = 10
plt.text(x,y, "Your comment")
This can help you with the font sizes:
How to change the font size on a matplotlib plot

Gravitational Waveform Plot From h5 File

I want to plot a waveform from two black-hole mergersI have a .h5 file that I got from a public waveform catalog. I I am kind of a beginner with using python so I don't really know what to do in this situation. I have a .h5 file that has a .dat file inside that I want to use to make a plot. I got the file from a public waveform catalog at:
http://www.black-holes.org/waveforms/data/DisplayDownloadPage.php/?id=SXS:BBH:0001#
the name of the file is :
rhOverM_Asymptotic_GeometricUnits.h5
it is in the Lev5 directory. The contents of the .h5 file are described in:
https://www.black-holes.org/waveforms/docs.html
There is a dataset in the file that I think describes the waveform that I want to plot. The problem is that I don't know how to get into the data set. I have gotten as far as doing:
import numpy as np
import h5py
from pylab import plot,show
f = h5.py.File("rhOverM_Asymptotic_GeometricUnits.h5","r")
ks = f.keys()
From here I don't know how to create the x and y axis that would go into the plot function. I am assuming that I need another attribute that belongs to the h5py module, but I am not even sure if I am using the right terminology. Any help would be appreciated.
Try this:
import matplotlib.pyplot as plt
import h5py
f = h5py.File("rhOverM_Asymptotic_GeometricUnits.h5", "r")
data = f['Extrapolated_N2.dir/Y_l2_m-1.dat']
plt.plot(data[:, 0], data[:, 1], label='column1')
plt.plot(data[:, 0], data[:, 2], label='column2')
plt.legend()
plt.show()

Categories

Resources