name "plot" is not defined - matplotlib

I'm trying to plot some data using matplotlib with the code below.
import matplotlib.pyplot as plt
import numpy as np
data_x = np.linspace(0, 10, 100)
data_y = 10 * np.exp(-data_x)
np.savetxt('tabelle1.txt', np.column_stack([data_x, data_y]), header='U I')
x, y = np.genfromtxt('tabelle1', unpack=True)
plt.plot(x, y, 'rx')
plt.xlabel(r'$x$')
plt.ylabel(r'$y$')
plt.yscale('log')
plt.tight_layout()
plt.savefig('loesung.pdf')
However, this generates an error saying NameError: name plot is not defined.
How can I fix this?

please try
#Add this script
import matplotlib
#Before
import matplotlib.pyplot as plt

Related

I have been trying to embed my matplotlib graph into a pyqt5 application with a moving graph any help is appreciated

This code displays a moving graph with two lines, and the data is saved to a CSV file with the code that makes the data. I have tried to create a canvas class using the pyqt5 imports, but I am struggling with where exactly to put the matplotlib code.
from itertools import count
import matplotlib.pyplot as plt
import pandas as pd
from matplotlib.animation import FuncAnimation
plt.style.use('fivethirtyeight')
x_vals = []
y_vals = []
index = count()
def animate(i):
data = pd.read_csv("C:/Users/Khata/PycharmProjects/LiveData1/venv/data.csv")
x = data['x_value']
y1 = data['total_1']
y2 = data['total_2']
plt.cla()
plt.plot(x, y1, label='Channel 1')
plt.plot(x, y2, label='Channel 2')
plt.legend(loc='upper left')
plt.tight_layout()
ani = FuncAnimation(plt.gcf(), animate, interval=1000)
plt.tight_layout()
plt.show()

Matplotlib double legend

With my code I get 2 equations in the legend that are the same. I don't how why it is so. I just want to correct this by making it only one equation. How can I do that? This equation is the line fit result of some of the data below.
Thanks in advance!
import matplotlib.pyplot as plt
import numpy as np
import plotly.plotly as py
import plotly.tools as tls
from sympy import S, symbols
import sympy
y = [2.7,2.3,1.9,1.5,1.3,1.0,0.8,0.6,0.5,0.4,0.2,0.1,0.0,0.0,-0.20,-0.2]
y = [i*10**(-16) for i in y]
x = [0,0.05,0.10,0.15,0.20,0.25,0.30,0.40,0.45,0.50,0.55,0.60,0.65,0.70,0.75,0.80]
e_y = [10**(-17)]* 16
e_x = [0.001] * 16
fig= plt.figure()
ax = fig.add_subplot(111)
ax.errorbar(x,y, yerr=e_y,xerr=0.001,fmt='-o')
ax.set_title('Current vs. Potential')
ax.set_xlabel('Retarding Potential')
ax.set_ylabel('Photocell Current')
x=x[:7]
y=y[:7]
e_y=e_y[:7]
e_x=e_x[:7]
#line fit:
fit=np.polyfit(x,y,1)
fit_fn = np.poly1d(fit)
a=symbols("x")
line = sum(S(format(v))*a**i for i, v in enumerate(fit[::-1]))
eq_latex = sympy.printing.latex(line)
plt.plot(x,y,x,fit_fn(x),label="${}$".format(eq_latex))
plt.legend(fontsize='small')
plt.show()
I solved this using the following:
#import matplotlib.patches as mpatches
plt.plot(x,y,x,fit_fn(x))
eqn = mpatches.Patch(color='green',label="${}$".format(eq_latex))
plt.legend(handles=[eqn])
instead of
plt.plot(x,y,x,fit_fn(x),label="${}$".format(eq_latex))
plt.legend(fontsize='small')

matplotlib adding string to a an axis

import matplotlib.pyplot as plt
import numpy as np
ydata = [55,60,65,70,75,80]
xdata = [1,2,3,4,5,6]
plt.plot(xdata, ydata)
set(plt.gca,'XTickLabel',{'Jan','Feb','Mar','April','May','June'})
plt.show()
I am using matplotlib and trying to add text values to appear on the x axis.
I have tried to use the following code but get the following error message
set(plt.gca,'XTickLabel',
{'Jan','Feb','Mar','April','May','June'})
TypeError: set expected at most 1 arguments, got 3 I am not sure what this
is referring get current access I have set the value
Sets are a Python data structure, it has nothing to do with what you want here, you only need to use ax.set_xticklabels and ax.set_xticks to ensure all of them show in the plot:
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
ydata = [55,60,65,70,75,80]
xdata = [1,2,3,4,5,6]
ax.set_xticks(xdata)
ax.set_xticklabels(['Jan','Feb','Mar','April','May','June'])
plt.plot(xdata, ydata)
plt.show()

How can I draw scatter trend line on matplot? Python-Pandas

I want to draw a scatter trend line on matplot. How can I do that?
Python
import pandas as pd
import matplotlib.pyplot as plt
csv = pd.read_csv('/tmp/test.csv')
data = csv[['fee', 'time']]
x = data['fee']
y = data['time']
plt.scatter(x, y)
plt.show()
CSV
fee,time
100,650
90,700
80,860
70,800
60,1000
50,1200
time is integer value.
Scatter chart
I'm sorry I found the answer by myself.
How to add trendline in python matplotlib dot (scatter) graphs?
Python
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
csv = pd.read_csv('/tmp/test.csv')
data = csv[['fee', 'time']]
x = data['fee']
y = data['time']
plt.scatter(x, y)
z = np.polyfit(x, y, 1)
p = np.poly1d(z)
plt.plot(x,p(x),"r--")
plt.show()
Chart
With text:
from sklearn.metrics import r2_score
plt.plot(x,y,"+", ms=10, mec="k")
z = np.polyfit(x, y, 1)
y_hat = np.poly1d(z)(x)
plt.plot(x, y_hat, "r--", lw=1)
text = f"$y={z[0]:0.3f}\;x{z[1]:+0.3f}$\n$R^2 = {r2_score(y,y_hat):0.3f}$"
plt.gca().text(0.05, 0.95, text,transform=plt.gca().transAxes,
fontsize=14, verticalalignment='top')
You also can use Seaborn lmplot:
import seaborn as sns
import pandas as pd
from io import StringIO
textfile = StringIO("""fee,time
100,650
90,700
80,860
70,800
60,1000
50,1200""")
df = pd.read_csv(textfile)
_ = sns.lmplot(x='fee', y='time', data=df, ci=None)
Output:

controlling the number of x ticks in pyplot

I want to display all 13 x ticks, but the graph only shows 7 of them having two intervals.
plt.locator_params(axis='x',nbins=13)
Why doesn't above code work??
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import matplotlib.dates as dates
y = [0, 0.86, 0.826, 0.816, 0.807, 0.803, 0.804, 0.803, 0.802,0.81, 0.813, 0.813, 0.813]
times = pd.date_range('2015-02-25', periods=13)
fig, ax = plt.subplots(1)
fig.autofmt_xdate()
xfmt = dates.DateFormatter('%d-%m-%y')
ax.xaxis.set_major_formatter(xfmt)
plt.locator_params(axis='x',nbins=13)
ax.plot_date(times.to_pydatetime(), y, 'v-')
ax.xaxis.set_minor_locator(dates.WeekdayLocator(byweekday=(1),
interval=1))
ax.xaxis.set_minor_formatter(dates.DateFormatter('%d\n%a'))
ax.xaxis.grid(True, which="minor")
ax.yaxis.grid()
plt.tight_layout()
plt.show()
The warning should give you some clue why this is happening:
UserWarning: 'set_params()' not defined for locator of type <class 'pandas.tseries.converter.PandasAutoDateLocator'>
str(type(self)))
Use plt.xticks(times.to_pydatetime()) instead:
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import matplotlib.dates as dates
y = [0, 0.86, 0.826, 0.816, 0.807, 0.803, 0.804, 0.803, 0.802,0.81, 0.813, 0.813, 0.813]
times = pd.date_range('2015-02-25', periods=13)
fig, ax = plt.subplots(1)
fig.autofmt_xdate()
xfmt = dates.DateFormatter('%d-%m-%y')
ax.xaxis.set_major_formatter(xfmt)
ax.plot_date(times.to_pydatetime(), y, 'v-')
ax.xaxis.set_minor_locator(dates.WeekdayLocator(byweekday=(1),
interval=1))
plt.xticks(times.to_pydatetime())
ax.xaxis.set_minor_formatter(dates.DateFormatter('%d\n%a'))
ax.xaxis.grid(True, which="minor")
ax.yaxis.grid()
plt.tight_layout()
plt.show()