I´m trying to create some graphs from a dataframe I imported. The problem is I can create an only image with both graphs. I have this output:
And I´m looking for this Output:
Here is the code:
from pandas_datareader import data
import pandas as pd
import datetime
import matplotlib.pyplot as plt
df = pd.read_csv('csv.csv', index_col = 'Totales', parse_dates=True)
df.head()
df['Subastas'].plot()
plt.title('Subastadas')
plt.xlabel('Fechas')
plt.ylabel('Cant de Subastadas')
plt.subplot()
df['Impresiones_exchange'].plot()
plt.title('Impresiones_exchange')
plt.xlabel('Fechas')
plt.ylabel('Cant de Impresiones_exchange')
plt.subplot()
plt.show()
CSV data:
Totales,Subastas,Impresiones_exchange,Importe_a_pagar_a_medio,Fill_rate,ECPM_medio
Total_07/01/2017,1596260396,30453841,19742.04,3.024863813,0.733696498
Total_07/12/2017,1336604546,57558106,43474.29,9.368463445,0.656716233
Total_07/01/2018,1285872189,33518075,20614.4,4.872889166,0.678244085
Also, I would like to save the output in an xlsx file too!
Use plt.subplots() to define two separate Axes objects, then use the ax argument of df.plot() to associate a plot to an axis:
import pandas as pd
import matplotlib.pyplot as plt
f, (ax1, ax2) = plt.subplots(2,1,figsize=(5,10))
df['Impresiones_exchange'].plot(ax=ax2)
ax1.set_title('Impresiones_exchange')
ax1.set_xlabel('Fechas')
ax1.set_ylabel('Cant de Impresiones_exchange')
df['Subastas'].plot(ax=ax1)
ax2.set_title('Subastadas')
ax2.set_xlabel('Fechas')
ax2.set_ylabel('Cant de Subastadas')
Related
I have identified that the most time-consuming step in the execution of code is saving plots to memory. I'm using matplotlib for plotting and saving the plots. The issue is that I'm running several simulations and saving the plots resulting from these simulations; this effort is consuming an insane number of compute hours. I have verified that it is indeed the plotting that is doing the damage.
It seems that pyqtgraph renders and saves images comparatively faster than matplotlib. I want to know if something similar to the following lines of code could be implemented in pyqtgraph?
import matplotlib
matplotlib.use('Agg')
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
fig = plt.figure(figsize=(6, 2.5))
rows = 1
columns = 2
gs = gridspec.GridSpec(rows, columns, hspace=0.0,wspace=0.0)
aj=0
for specie in lines:
for transition in species[specie].items():
gss = gridspec.GridSpecFromSubplotSpec(2, 1, subplot_spec=gs[aj],hspace=0.0,height_ratios=[1, 3])
ax0 = fig.add_subplot(gss[0])
ax1 = fig.add_subplot(gss[1], sharex=ax0)
ax0.plot(fitregs[specie+transition[0]+'_Vel'],fitregs['N_residue'],color='black',linewidth=0.85)
ax1.plot(fitregs[specie+transition[0]+'_Vel'],fitregs['N_flux'],color='black',linewidth=0.85)
ax1.plot(fitregs[specie+transition[0]+'_Vel'],fitregs['Best_profile'],color='red',linewidth=0.85)
ax1.xaxis.set_minor_locator(AutoMinorLocator())
ax1.tick_params(which='both', width=1)
ax1.tick_params(which='major', length=5)
ax1.tick_params(which='minor', length=2.5)
ax1.text(0.70,0.70,r'$\chi^{2}_{\nu}$'+'= {}'.format(round(red_chisqr[aj],2)),transform=ax1.transAxes)
ax1.text(0.10,0.10,'{}'.format(specie+' '+transition[0]),transform=ax1.transAxes)
ak=ak+1
aj=aj+1
canvas = FigureCanvas(fig)
canvas.print_figure('fits.png')
Example output from the above code is
Cant figure out how to combine these two plots.
Here is the relevant code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
%pylab inline #Jupyter Notebook
df_state.head()
lm_orginal_plot.head()
outputs for .head()
df_state.loc['Alabama'][['month','total purchases',
'permit','permit_recheck']].plot(x='month',figsize=(6,3),linestyle='-', marker='o')
lm_original_plot.plot(x='month',figsize=(6,3),linestyle=':');
outputs for plots
This is how I would do this (not saying it is the best method or anything):
1) merge two dfs on month
all = df_state(lm_original_plot, on = 'month', how='left')
2) create figure (total is now column just like the other variables in
the first chart, so you can just add ‘total’ to your first chart code)
Not my work, just what a peer showed me.
I have data like this :
import pandas as pd
import matplotlib.pyplot as plt
index={'A','B','C','D','E'}
d={'typ':[1,2,2,2,1],'value':[10,25,15,17,13]}
df=pd.DataFrame(d,index=index)
I want to plot the dataframe in horizontal bars with different colors reffering to the column 'typ'
You can use the color parameter of matplotlib's barh function:
import pandas as pd
import matplotlib.pyplot as plt
index={'A','B','C','D','E'}
d={'typ':[1,2,2,2,1],'value':[10,25,15,17,13]}
df=pd.DataFrame(d,index=index)
# define the colors for each type
colors = {1:'blue', 2:'red'}
# plot the bars
plt.bar(range(len(df)), df['value'], align='center',
color=[colors[t] for t in df['typ']])
This question is related to plotting minor tick mars on the y-axis in a Python plot with
matplotlib.
Here is the code that I have:
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator
fig, ax = plt.subplots()
fig.set_facecolor('white')
x = [1,2,3]
plt.subplot(211)
plt.plot([1,2,3], label="test1")
plt.plot([3,2,1], label="test2")
plt.xticks()
plt.yticks()
ax.yaxis.set_minor_locator(MultipleLocator(5))
plt.show()
When I generate this plot, I am not getting any minor tick marks.
I have attached here the plot that this code gives me.
Is it possible for me to display the minor tick marks for the y-axis here?
You can set what ticks you want in plt.yticks() , the input can be a numpy array which you generate beforehand
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator
import numpy as np
fig, ax = plt.subplots()
fig.set_facecolor('white')
yticks = np.arange(1,3,0.2)
x = [1,2,3]
plt.subplot(211)
plt.plot([1,2,3], label="test1")
plt.plot([3,2,1], label="test2")
plt.xticks()
plt.yticks(yticks)
ax.yaxis.set_minor_locator(MultipleLocator(5))
plt.show()
which gives you :
I am able to plot Multiple data sets in a single plot and a plot with a single data set with a break in the y-axis(This page helped me) separately. But What I would like to do is to remove the portion from 10^46 to 10^58 in the following plot.! The code which I used to plot is
from numpy import *
from pylab import *
from matplotlib import rc, rcParams
import matplotlib.pyplot as plt
import numpy as np
rc('text',usetex=True)
rc('font',**{'family':'serif','serif':['Computer Modern']})
x_1=np.linspace(5e13, 8e14, 201)
z = np.linspace(0, np.pi, 201)
y_1 =np.cos(z)*1e43
x_2=np.linspace(5e13, 1e15, 201)
y_2 =np.cos(z)*1e61
x_3=np.linspace(3e13, 1e15, 201)
y_3 =np.tan(z)*1e63
run_1,=plt.plot(x_1, y_1, '.b')
run_2,=plt.plot(x_2, y_2, '.g')
run_3,=plt.plot(x_3, y_3,'.r')
plt.yscale('log')
plt.xscale('log')
plt.xlim([40000000000000,2000000000000000])
plt.legend((run_1, run_2,run_3), ('CR Flux','Gas Ensrgy','Total Energy'),scatterpoints=1, loc='lower right', ncol=1, fontsize=12)
# Turn on a grid
grid(True)
savefig('camp_line.png')
show()
How to achieve this? Is there any function for achieving this?