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")
Related
I'm trying to plot netcdf raster values of snowfall data in a text format overlaying what I currently have (mentioned further below). Example, something like this below:
Example
This is all the relevant code I have so far. I excluded the non relevant code. I tried plt.text and it gave me "ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()"
What I have plotted so far
import numpy
from datetime import datetime
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import cartopy.mpl.ticker as cticker
import matplotlib.pyplot as plt
from matplotlib import ticker, patheffects
from metpy.units import units
import numpy as np
import numpy.ma as ma
from scipy.ndimage import gaussian_filter, maximum_filter, minimum_filter
import xarray as xr
from metpy.plots import USCOUNTIES
from gradient import Gradient
import pandas as pd
import matplotlib.colors as col
#Open NOAA Snowfall dataset
ds = xr.open_dataset('sfav2_CONUS_2021093012_to_2022042512.nc')
ds
lat = ds.lat
lon = ds.lon
#converts snowfall data to inches
snowdata = ds['Data'] * 39
plt.text(lon, lat, snowdata, transform=datacrs)
As far as I know there isn't a vectorized way of plotting text (plt.text or plt.annotated). So you'll have to loop over the arrays and plot each point.
import matplotlib.pyplot as plt
import matplotlib.patheffects as PathEffects
import cartopy.crs as ccrs
import numpy as np
data = np.random.rand(18, 9)
lons, lats = np.mgrid[-17:18:2, 8:-9:-2]
lons = lons * 10
lats = lats * 10
fig, ax = plt.subplots(figsize=(10, 5), dpi=86, facecolor="w", subplot_kw=dict(projection=ccrs.EqualEarth()))
ax.pcolormesh(lons, lats, data, cmap="coolwarm", alpha=.2, transform=ccrs.PlateCarree())
ax.coastlines()
for val, lat, lon in zip(data.flat, lats.flat, lons.flat):
ax.text(
lon, lat, f"{val:1.1f}", ha="center", va="center", transform=ccrs.PlateCarree(),
path_effects=[PathEffects.withStroke(linewidth=3, foreground="w", alpha=.5)],
)
I am already having Tkinter(someone said to install a tkinter)
code used:
imports are:
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()
if u want to view the data-set then it is :
df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/diabetes.csv")
code used to plot boxplot in jupyter notebook
fig, ax = plt.subplots(figsize = (20,20))
sns.boxplot(data = df,ax = ax)
)
I was supposed to add in my import's
%matplotlib inline
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?
from abupy import ABuSymbolPd
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
tsla_df = ABuSymbolPd.make_kl_df('usTSLA', n_folds=8)
tsla_df [['close', 'volume']].plot (subplots = True, style = ['r', 'g'],
grid = True)
print tsla_df [ ['close', 'volume']]
plt.show()
tsla_df.info()
tsla_df.describe(include = "all")
In above python code, I hope last code list the statistical of tsla_df, but it does not and also never give any error information. Anybody has any idea?
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()