Why histogram ticks showing different answers in gui in compare with non-gui? - pandas

I am using jupyter notebook and I want to draw histograms. When I do not use GUI it is okay and everything is shown correctly but when I use the Tkinter version of the code, all bars in histogram are shifted to left so the first bar is missing.(e.g: It should be 4 on a,3 on b,9 on c but it shows 3 on a,9 on b, where a,b and c are ticks)
this is the first code i do not use gui:
import Tkinter as tk
from Tkinter import*
import tkMessageBox
import tkFileDialog
import pandas as pd
import pyautogui
import os
from PIL import Image, ImageTk
from tkinter import ttk
import pylab as plt
from matplotlib.ticker import (MultipleLocator, FormatStrFormatter,
AutoMinorLocator)
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
select1=pd.DataFrame()
select2=pd.DataFrame()
year1=1396
year2=1395
select1=df.loc[(df['yearj']==year1)]
select2=df.loc[(df['yearj']==year2)]
x=select1['monthj'].values.tolist()
y=select2['monthj'].values.tolist()
plt.xlabel('month')
plt.ylabel('number of orders')
bins=[1,2,3,4,5,6,7,8,9,10,11,12,13]
axx=plt.subplot()
axx.xaxis.set_major_locator(MultipleLocator(1))
axx.xaxis.set_major_formatter(FormatStrFormatter('%d'))
plt.hist(y,bins,rwidth=0.8)
plt.hist(x,bins,rwidth=0.8, alpha=0.6)
and the output is:
enter image description here
and here is second code:
import pandas as pd
import numpy
import pylab as plt
from matplotlib.ticker import (MultipleLocator, FormatStrFormatter,
AutoMinorLocator)
def compare_months(df,hh):
compmon = tk.Toplevel(h
bins=[1,2,3,4,5,6,7,8,9,10,11,12,13]
select1=pd.DataFrame()
select2=pd.DataFrame()
year1=1396
year2=1395
select1=df.loc[(df['yearj']==year1)]
select2=df.loc[(df['yearj']==year2)]
xr=select1['monthj'].values.tolist()
yr=select2['monthj'].values.tolist()
xr.sort(key=int)
yr.sort(key=int)
f = Figure(figsize=(7,6), dpi=80)
f.add_axes([0.15, 0.15,0.8,0.7])
canvas = FigureCanvasTkAgg(f, master=compmon)
canvas.get_tk_widget().grid(row=4, column=5, rowspan=8)
p = f.gca()
p.set_xlabel('month', fontsize = 10)
p.set_ylabel('number of orders', fontsize = 10)
p.hist(yr,bins,rwidth=0.8)
p.hist(xr,bins,rwidth=0.8, alpha=0.6)
p.xaxis.set_major_formatter(FormatStrFormatter('%d'))
p.xaxis.set_major_locator(MultipleLocator(1))
but=Button(compmon, text="ok", command=compare_months(df,root))
but.grid(row=2,column=2)
and the output is:enter image description here
Why does this happen?

Related

How to show the peaks of pmf by matplotlib and scipy?

this is the code(I want to know the peak of the picture but I don't know how to add this kind of code)
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
from scipy import stats
n=25
p=0.6
k=np.arange(0,50)
#the pmf forming
picture=stats.binom.pmf(k,n,p)
print(picture)
mpl.rcParams['font.sans-serif'] = [u'SimHei']
mpl.rcParams['axes.unicode_minus'] = False
mean,var,skew,kurt=stats.binom.stats(n,p,moments='mvsk')
print(mean,var,skew,kurt)
#the picture forming
plt.plot(k,picture,'o-')
plt.grid(True)
plt.show()
You can use scatter
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
from scipy import stats
n=25
p=0.6
k=np.arange(0,50)
#the pmf forming
picture=stats.binom.pmf(k,n,p)
mpl.rcParams['font.sans-serif'] = [u'SimHei']
mpl.rcParams['axes.unicode_minus'] = False
mean,var,skew,kurt=stats.binom.stats(n,p,moments='mvsk')
print(mean,var,skew,kurt)
#the picture forming
plt.plot(k,picture,'o-')
plt.grid(True)
# the two new lines
max_ind = np.argmax(picture)
plt.scatter(x=k[max_ind],y=picture[max_ind],c='r',s=100,zorder=10)
and this produces

Why df.interpotale() doesn't work in my python3? why does it return the exact same dataframe withut any interpolation?

my code for df.interpolate was:
import pandas as pd
import numpy as np
import xlrd
from IPython.display import display
from scipy import interpolate
pd.set_option('display.max_rows',54100)
df = pd.read_excel(r'C:\Users\User\Desktop\tanvir random practice\gazipur.xlsx', parse_date=["DateTime"], index_col='DateTime']
df.interpolate(method="linear").bfill()
display(df)

matplotlib code does not shows anything on output

I am following this here: https://matplotlib.org/users/image_tutorial.html
The code is this:
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
img = mpimg.imread('1.jpg')
I am trying to output something, but when I execute the code, I get nothing... Shouldn't I get a matrix as output?

seaborn/Matplotlib export EPS causes "falling back to Agg renderer"

Consider the MWE below. This will cause (Seaborn 0.7.1, Matplotlib 1.5.1):
/usr/local/lib/python3.5/dist-packages/matplotlib/tight_layout.py:222:
UserWarning: tight_layout : falling back to Agg renderer
warnings.warn("tight_layout : falling back to Agg renderer")
How to fix this?
MWE
import matplotlib
matplotlib.use('ps')
import pandas as pd
import random
import seaborn as sns
import matplotlib.pyplot as plt
ds = pd.DataFrame()
ds['x'] = random.sample(range(1, 100), 25)
ds['y'] = random.sample(range(1, 100), 25)
p = sns.jointplot(x = ds['x'],y = ds['y'],linewidth=1,edgecolor='black',alpha=0.3,stat_func=None)
plt.savefig("test.eps")

Map offsite with matplotlib(using geopandas and cartopy)

I have created a map like this:
The problem with it is that on the right side of the map is always a little bit offsite. I have set the bounds to:
ax.set_xlim(-215800,
1000000)
ax.set_ylim(3402659,
4879248)
No matter how I increase the xlim, or set margin the right side is still outside the bounds of the canvas. Can somebody help?
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from osgeo import ogr
import matplotlib.pyplot as plt
import matplotlib as mpl
import rasterio
import cartopy.crs as ccrs
import geopandas
from geopandas import *
from matplotlib import colors
MediumApple='#55FF00'
Cantaloupe='#FFA77F'
Marsred='#FF0000'
crs = ccrs.UTM(zone=10)
ax = plt.axes(projection=crs)
import matplotlib.patches as mpatches
for county in CAcountylist:
with rasterio.drivers():
with rasterio.open(r"CA\%s \%s.tif"%(county,county),"r") as src:
meta = src.meta
im=src.read().astype('f')
im=np.transpose(im,[1,2,0])
print im.shape
print im.min(),im.max()
im[im==0]=np.nan
im=im.squeeze()
xmin = src.transform[0]
xmax = src.transform[0] + src.transform[1]*src.width
print src.width,src.height
ymin = src.transform[3] + src.transform[5]*src.height
ymax = src.transform[3]
colors=[MediumApple,Cantaloupe,Marsred]
cmap=mpl.colors.ListedColormap([MediumApple,Cantaloupe,Marsred])
bounds_color=[1,1,2,2,3,3]
norm=mpl.colors.BoundaryNorm(bounds_color,cmap.N)
print xmin,xmax,ymin,ymax
ax.imshow(im, origin='upper', extent=[xmin,xmax,ymin,ymax], transform=crs, interpolation='nearest',cmap=cmap,norm=norm)
df=GeoDataFrame.from_file(r"\CACounty.shp")
df=df.to_crs(epsg=26910)
df.plot(axes=ax,alpha=0)
bounds = df.geometry.bounds
ax.set_xlim(-215800,
1000000)
ax.set_ylim(3402659,
4879248)
low_patch = mpatches.Patch(color='#55FF00', label='Low')
Moderate_patch = mpatches.Patch(color='#FFA77F', label='Moderate')
High_patch = mpatches.Patch(color='#FF0000', label='High')
plt.legend(handles=[low_patch,Moderate_patch,High_patch],loc=3)
plt.show()