How to find the y from given x on fit line? - numpy

I ploted a fit line using numpy and matplotlib of a graph and I need to find the spesific y value for a x value that I determine on the line. Is it possible?
plt.figure(figsize=(12,7), dpi=600)
a, b = np.polyfit(x.x, x.v, 1)
plt.plot(x.x, x.v, linestyle='none', marker='v', color='#33E0FF', markeredgecolor='#FD8100', markersize=10)
plt.plot(x.x, a*x.x + b, color='#FF5733')
plt.xlabel("x(cm)")
plt.ylabel("v^2(cm^2/s^2")
plt.grid(True)
plt.xticks(np.arange(20, 81, 5))
plt.yticks(np.arange(900, 3500, 250))
plt.show()
this is graph code and i want to find which y values for x=55

Your a,b are the coefficients of the line you fitted.
you are plotting the line in this line of code:
plt.plot(x.x, a*x.x + b, color='#FF5733')
so if you want a y value for a specific x it would look something like this:
y_x_1 = a*x_1+b

Related

Numpy: Is there any simple way to solve equation in form Ax = b such that some x's takes fixed values

So basically I want to solve Ax = b but I want the value of x1 to always be equation to say 4.
For example, if A is 3x3 and x is 3x1 then the answer of the above equation should be in form x = [4, x2, x3]
if always x1=4, then x1 is no longer a unknown --> insert x1=4 in each place of the system and simplify the equations (algebraically = manually) --> you will get a system where A is 2x2 and x is 2x1.

How to graph events on a timeline

I tracked all the movies I watched in 2019 and I want to represent the year on a graph using matplotlib, pyplot or seaborn. I saw a graph by a user who also tracked the movies he watched in a year:
I want a graph like this:
How do I represent each movie as an 'event' on a timeline?
For reference, here is a look at my table.
(sorry if basic)
I've made an assumption (from your comment) that your date column is type str. Here is code that will produce the graph:
Modify your pd.DataFrame object
Firstly, a function to add a column to your dataframe:
def modify_dataframe(df):
""" Modify dataframe to include new columns """
df['Month'] = pd.to_datetime(df['Date'], format='%Y-%m-%d').dt.month
return df
The pd.to_datetime function converts the series df['Date'] to a datetime series; and I'm creating a new column called Month which equates to the month number.
From this column, we can generate X and Y coordinates for your plot.
def get_x_y(df):
""" Get X and Y coordinates; return tuple """
series = df['Month'].value_counts().sort_index()
new_series = series.reindex(range(1,13)).fillna(0).astype(int)
return new_series.index, new_series.values
This takes in your modified dataframe, creates a series that counts the number of occurrences of each month. Then if there are any missing months, fillna fills them in with a value of 0. Now you can begin to plot.
Plotting the graph
I've created a plot that looks like the desired output you linked.
Firstly, call your functions:
df = modify_dataframe(df)
X, Y = get_x_y(df)
Create the canvas and axis to plot on to.
fig = plt.figure(figsize=(12,5))
ax = fig.add_subplot(1, 1, 1, title='Films watched per month - 2019')
Generate x-labels. This will replace the current month int values (i.e. 1, 2, 3...) on the x-axis.
xlabels = [datetime.datetime(2019, i, 1).strftime("%B") for i in list(range(1,13))]
ax.set_xticklabels(xlabels, rotation=45, ha='right')
Set the x-ticks, and x-label.
ax.set_xticks(range(1,13))
ax.set_xlabel('Month')
Set the y-axis, y-lim, and y-label.
ax.set_yticks(range(0, max(s1.values)+2))
ax.set_ylim(0, max(s1.values)+1)
ax.set_ylabel('Count')
To get your desired output, fill underneath the graph with a block-colour (I've chosen green here but you can change it to something else).
ax.fill_between(X, [0]*len(X), Y, facecolor='green')
ax.plot(X, Y, color="black", linewidth=3, marker="o")
Plot your graph!
plt.show() # or plt.savefig('output.png', format='png')

How to show following data with colors and color bar. What will be suitable command for this? [duplicate]

I want to make a scatterplot (using matplotlib) where the points are shaded according to a third variable. I've got very close with this:
plt.scatter(w, M, c=p, marker='s')
where w and M are the data points and p is the variable I want to shade with respect to.
However I want to do it in greyscale rather than colour. Can anyone help?
There's no need to manually set the colors. Instead, specify a grayscale colormap...
import numpy as np
import matplotlib.pyplot as plt
# Generate data...
x = np.random.random(10)
y = np.random.random(10)
# Plot...
plt.scatter(x, y, c=y, s=500) # s is a size of marker
plt.gray()
plt.show()
Or, if you'd prefer a wider range of colormaps, you can also specify the cmap kwarg to scatter. To use the reversed version of any of these, just specify the "_r" version of any of them. E.g. gray_r instead of gray. There are several different grayscale colormaps pre-made (e.g. gray, gist_yarg, binary, etc).
import matplotlib.pyplot as plt
import numpy as np
# Generate data...
x = np.random.random(10)
y = np.random.random(10)
plt.scatter(x, y, c=y, s=500, cmap='gray')
plt.show()
In matplotlib grey colors can be given as a string of a numerical value between 0-1.
For example c = '0.1'
Then you can convert your third variable in a value inside this range and to use it to color your points.
In the following example I used the y position of the point as the value that determines the color:
from matplotlib import pyplot as plt
x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
y = [125, 32, 54, 253, 67, 87, 233, 56, 67]
color = [str(item/255.) for item in y]
plt.scatter(x, y, s=500, c=color)
plt.show()
Sometimes you may need to plot color precisely based on the x-value case. For example, you may have a dataframe with 3 types of variables and some data points. And you want to do following,
Plot points corresponding to Physical variable 'A' in RED.
Plot points corresponding to Physical variable 'B' in BLUE.
Plot points corresponding to Physical variable 'C' in GREEN.
In this case, you may have to write to short function to map the x-values to corresponding color names as a list and then pass on that list to the plt.scatter command.
x=['A','B','B','C','A','B']
y=[15,30,25,18,22,13]
# Function to map the colors as a list from the input list of x variables
def pltcolor(lst):
cols=[]
for l in lst:
if l=='A':
cols.append('red')
elif l=='B':
cols.append('blue')
else:
cols.append('green')
return cols
# Create the colors list using the function above
cols=pltcolor(x)
plt.scatter(x=x,y=y,s=500,c=cols) #Pass on the list created by the function here
plt.grid(True)
plt.show()
A pretty straightforward solution is also this one:
fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(8,8))
p = ax.scatter(x, y, c=y, cmap='cmo.deep')
fig.colorbar(p,ax=ax,orientation='vertical',label='labelname')

3D Density visualisation with matplotlib

I am trying to plot a 3D column with associated density.
Specifically, I have a .txt file with 4 separate columns x, y, z, density. The first 3 columns are the cartesian coordinates of the column, density a list of density values associated with each cross-section, at height z, of the column.
I can plot the column with a colormap as follows
x=np.linspace(-1, 1, 100)
z=np.linspace(-20, 5, 50)
Xc, Zc=np.meshgrid(x, z)
Yc = np.sqrt(1-Xc**2)
# Draw parameters
rstride = 1
cstride = 1
surf1 = ax.plot_surface(Xc, Yc, Zc, alpha=1., rstride=rstride, cstride=cstride,antialiased=False, cmap=cm.coolwarm,linewidth=0)
surf2 = ax.plot_surface(Xc, -Yc, Zc, alpha=1., rstride=rstride, cstride=cstride, antialiased=False, cmap=cm.coolwarm,linewidth=0)
and I can associate a colormap to z
fig.colorbar(surf1, shrink=0.5, aspect=5)
I would like to associate the colormap to the values in the fourth column, while maintaining the plotted dimensions of the cylinder constant.
I would appreciate any help on the matter.
Thanks.

Matplotlib: how to control the plot interval of x axis?

I'm plotting the degree of freedom against the square error,:
plt.plot([1,2,3,4], [0.5,0.6,0.9,0.85],'-')
It will produce
The problem is that ,the x ax is has 0.5 interval, and does not make sense in this context. Because there is simply no 1.5 degree of freedom.
How can I make the x axis into [1,2,3,4,], instead of [1, 1.5, 2, ...]?
Just add directly the positions and the strings you want to put in the x axis. Using your example:
import matplotlib.pyplot as plt
x = [1,2,3,4]
y = [0.5,0.6,0.9,0.85]
plt.plot(x,y,'-')
plt.xticks(list(range(1,max(x)+1)),[str(i) for i in range(1,max(x)+1)])
plt.grid()
plt.show()
, which results in:
You have to set the XTick 1 to 4, by 1 1:1:4 like below
plot([1,2,3,4], [0.5,0.6,0.9,0.85],'-');
set(gca,'XTick',1:1:4);
or
p = plot([1,2,3,4], [0.5,0.6,0.9,0.85],'-');
set(p,'XTick',1:1:4);