Plotting Pandas into subplots - python-3.x

da is my dataframe. I want to make this figure into one subplot out of 2 that I will have. When I add plt.subplots(2,1,2) for this figure it ends up separating this figure into a separate figure and the subplot is an empty figure.
How can I make this code into a subplot?
-Thank you in advance, I am a newbie in python.
ax1 = da.plot(rot = 90, title ='Pre-Folsom Dam Spring Recession')
ax1.set_xlabel('Water Year Day')
ax1.axhline( y = float(fSP_Mag) , xmin=0, xmax=35,color ='r', linestyle='--',zorder=0,label= 'Magnitude')
ax1.axvline(x=float(fSP_Tim), color ='r',linestyle='--', label='Timing')
ax1.legend(framealpha=1, frameon=True)

import pandas as pd
import matplotlib.pyplot as plt
data=pd.DataFrame({"col1":[1,2,3,4,5],"col2":[2,4,6,8,10]})
fig=plt.figure()
ax1=fig.add_subplot(2,1,1)
ax2=fig.add_subplot(2,1,2)
data["col1"].plot(ax=ax1)
data["col2"].plot(ax=ax2)
Create a plt.figure() and assign subplots to ax1 and ax2.Now plot the dataframe using these axes.
Reference:-
Pyplot

Related

plotting time and temperature in xy plot

I want to plot a xy plot where x axis contain temperature values(first column) and y axis contain time in hr:min:sec(second column) .
8.8900 06:09:95.50
9.4500 06:09:00.56
10.5800 08.06:95.48
11.6500 09:07:73.58
56.3650 00:08:00.47
85.7823 07:01:03.23
I just want to plot a xy plot.
I tried code
import numpy as np
import matplotlib.pyplot as plt
data=np.loadtxt("inpdata.txt")
plt.plot(data[:,0],data[:,1])
plt.show()
But it does not give plot.hope experts may help.Thanks.
The simplest approach would be to use pandas.
Load the file as whitespace delimited file into pandas.DataFrame object as:
import pandas as pd
from matplotlib import pyplot as plt
df = pd.read_csv('inpdata.txt', names=['temp', 'time'], delim_whitespace=True)
Then create a line plot with time as x axis:
df.plot.line(x='time')
and show the plot
plt.show()

Break a pandas line plot at specific date

I have a time-series dataframe with missing data for some time period. I would like to create a line plot and break a line where there is missing data.
data_site1_ave[["samples", "lkt"]].plot(figsize=(15,4), title = "Site 1", xlabel='')
Is it possible to create a gap, let's say from 2018-05-01 to 2018-10-30 in the line plot?
Yes, you can create arbitrary gaps by simply calling df.plot() several times, on the appropriate slices of the full dataframe. To make everything appear in the same plot, you can pass the ax keyword argument to plt.plot() via the df.plot() method. Turn the legend off for all but one call, so that the legend only has the one entry.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# create sample time series
N = 365
np.random.seed(42)
x = pd.date_range('2018-01-01', freq='d', periods=N)
y = np.cumsum(np.random.rand(N, 1) - 0.5)
df = pd.DataFrame(y, columns=['y'], index=x)
# plot time series with gap
fig, ax = plt.subplots()
df.loc[:'2018-05-01'].plot(ax=ax, c='blue')
df.loc['2018-10-31':].plot(ax=ax, c='blue', legend=False);

X and Y label being cut in matplotlib plots

I have this code:
import pandas as pd
from pandas import datetime
from pandas import DataFrame as df
import matplotlib
from pandas_datareader import data as web
import matplotlib.pyplot as plt
import datetime
start = datetime.date(2016,1,1)
end = datetime.date.today()
stock = 'fb'
fig = plt.figure(dpi=1400)
data = web.DataReader(stock, 'yahoo', start, end)
fig, ax = plt.subplots(dpi=720)
data['vol_pct'] = data['Volume'].pct_change()
data.plot(y='vol_pct', ax = plt.gca(), title = 'this is the title \n second line')
ax.set(xlabel="Date")
ax.legend(loc='upper center', bbox_to_anchor=(0.32, -0.22), shadow=True, ncol=2)
plt.savefig('Test')
This is an example of another code but the problem is the same:
At bottom of the plot you can see that the legend is being cut out. In another plot of a different code which i am working on, even the ylabel is also cut when i save the plot using plt.savefig('Test').How can i can fix this?
It's a long-standing issue with .savefig() that it doesn't check legend and axis locations before setting bounds. As a rule, I solve this with the bbox_inches argument:
plt.savefig('Test', bbox_inches='tight')
This is similar to calling plt.tight_layout(), but takes all of the relevant artists into account, whereas tight_layout will often pull some objects into frame while cutting off new ones.
I have to tell pyplot to keep it tight more than half the time, so I'm not sure why this isn't the default behavior.
plt.subplots_adjust(bottom=0.4 ......)
I think this modification will satisfy you.
Or maybe you can relocate the legend to loc="upper left"
https://matplotlib.org/api/_as_gen/matplotlib.pyplot.subplots_adjust.html
please also checked this issue which raised 8 years ago..
Moving matplotlib legend outside of the axis makes it cutoff by the figure box

how to make scatter plot of two columns and divide x_axis in 3 column f1,f2,and f3

I have dataframe i want to draw a scattor plot by dividing plot in 2 regions in region one only plot f_x_f1 vs A_x_f1, and in region2 plot f_x_f2 vs A_x_f2
please if someone can provide better solution for this problem
here is example of my dataframe
df=pd.DataFrame({'f_x_f1':[0.3,0.28,0.34],'A_x_f1':[0.003,0.28,0.034],'f1':[0.4,0.4,0.4],'f_x_f2':[0.91,0.88,0.96],'A_x_f2':[0.003,0.28,0.034],'f2':[1.3,1.3,1.3]})
Here, using matplotlib!
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
### making some sample data
df = pd.DataFrame({"f_x_f1": np.random.randint(1,100,100)
, "A_x_f1": np.random.randint(1,100,100)
, "f_x_f2": np.random.randint(1,100,100)
, "A_x_f2": np.random.randint(1,100,100) })
fig, ax = plt.subplots(nrows=1, ncols=2)
ax[0].scatter(df.f_x_f1,df.A_x_f1)
ax[0].set_title("f_x_f1 vs A_x_f1")
ax[1].scatter(df.f_x_f2,df.A_x_f2)
ax[1].set_title("f_x_f2 vs A_x_f2")
OUTPUT:

how can i plot the graph for csv data in matplotlib

can you please tell me how to plot the graph for csv data.
csv file have x,y,depth,color values i want to plot the depth and color for x and y axis,i goggled many times but i didn't find anything properly.so please guide me how to plot the graph for that values?
this is i tried :
from matplotlib import pyplot as plt
from matplotlib import style
import pandas as pd
data=pd.read_csv("Tunnel.csv",names=['x','y','z','color'])
data1 =data[data.z==0]
print (data1)
# plt.plot(data[data.x],data[data.y])
plt.ylabel('yaxis')
plt.xlabel('xaxis')
plt.title('Tunnel 2d')
plt.show()
my data is given bellow
I'm assuming that you want the first two columns to be used as plot axis and columns 3 and 4 as plot data.
from matplotlib import pyplot as plt
import pandas as pd
data = pd.read_csv("Tunnel.csv")
x = stats[stats.columns[2]]
y = stats[stats.columns[3]]
xlab = list(stats)[0] #x-axis label
ylab = list(stats)[1] #y-axis label
fig, pli = plt.subplots()
pli.show()
#Assuming it's a line graph that you want to plot
line, = pli.plot(x, y, color='g', linewidth=5, label='depth vs color')
plt.xlabel(xlab)
plt.ylabel(ylab)
plt.title(title)
fig.savefig('./Directory/Graph.png')
I am assuming that you want the color and depth as text annotations.
import stuff
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
create the df
dep=list(np.random.randint(0,100,10))
col=list(np.random.randint(0,100,10))
y=[int(x/3)+1 for x in range(0,10)]
x=list(range(0,10))
my_df=pd.DataFrame({'x':x,'y':y,'colour':col,'depth':dep})
create the annotate column
my_df['my_text']='c= '+my_df.colour.astype(str)+','+'d= '+my_df.depth.astype(str)
plot it
plt.figure(figsize=(20,10))
plt.plot(my_df.x,my_df.y,'o')
for i, txt in enumerate(my_df['my_text']):
plt.annotate(txt, (x[i],y[i]), size=10, xytext=(0,0), ha='left', textcoords='offset points', bbox=dict(facecolor='none', edgecolor='red'))
plt.ylabel('yaxis')
plt.xlabel('xaxis')
plt.title('Tunnel 2d')
plt.show()
Result

Resources