Map and scatter not working (Mplleaflet) - python-3.x

The following code is an attempt to put points on a map via mplleaflet in a Jupyter notebook. It works for the first 3 points but not when including the 4th. It must be something other than this point - I can plot the 4th and 5th together for example. I want to be able to plot all the points including after the pound signs. Any ideas what's going wrong?
%matplotlib inline
import mplleaflet
import matplotlib.pyplot as plt
lats = [54.3256, 53.2692, 53.8242, 53.2178] #, 51.9978, 52.42, 53.1658, 54.292, 52.127, 51.505, 51.478, 51.35]
lons = [2.9356, 3.6278, 2.9453, 3.2203] #, 3.275, -1.83, 0.5239, -1.535, 0.956, -1.993, -0.461, 1.3667]
plt.hold(True)
plt.plot(lons, lats, 'rs')
mplleaflet.display()
EDIT: I've given up trying to use plt.scatter as this does not seem to work at all.
EDIT 2: seems I just needed to get rid of the 'mplleaflet.display()' suggested in the original code I was trying to make work. Hold is now depreciated however - see alternative below.

Try this:
import mplleaflet
import matplotlib.pyplot as plt
lats = [54.3256, 53.2692, 53.8242, 53.2178]
lons = [2.9356, 3.6278, 2.9453, 3.2203]
fig = plt.figure() #This is missing in your code.
plt.plot(lons, lats, 'r.')
#And after this call the funtion:
mplleaflet.display(fig=fig)
#It will display the matplotlib object created by plot function

Related

Python matplotlib custom colorbar for plotted lines with manually assigned colors

I'm trying to define a colorbar for the following type of plot.
import matplotlib.pyplot as plt
import numpy as np
for i in np.arange(0,10,0.1):
plt.plot(range(10),np.ones(10)*i,c=[i/10.,0.5,0.25])
plt.show()
This is just a simplified version of my actual data, but basically, I'd like a series of lines plotted and colored by another variable with a colorbar key. This is easy to do in scatter, but I can't get scatter to plot connected lines. Points are too clunky. I know this sounds like basic stuff, but I'm having a helluva time finding a simple solution ... what obvious solution am I missing?
You can build a custom color map and a mappable from it, then pass to colorbar:
from matplotlib.cm import ScalarMappable
from matplotlib.colors import Normalize
import matplotlib.colors as mcolors
color_list = [(i/10, 0.5,0.25) for i in np.arange(0,10,0.1)]
cmap = mcolors.LinearSegmentedColormap.from_list("my_colormap", color_list)
cmappable = ScalarMappable(norm=Normalize(0,10), cmap=cmap)
plt.figure(figsize=(10,10))
for j,i in enumerate(np.arange(0,10,0.1)):
plt.plot(range(10),np.ones(10)*i,c=color_list[j])
plt.colorbar(cmappable)
plt.show()
Output:

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

Programming a simple Python Stock Service. How can I program this to only show the graph for only a few seconds?

This is the current programs with no errors at all...
from alpha_vantage.timeseries import TimeSeries
from alpha_vantage.techindicators import TechIndicators
from matplotlib.pyplot import figure
import matplotlib.pyplot as plt
# Your key here
key = 'W01B6S3ALTS82VRF'
# Chose your output format, or default to JSON (python dict)
ts = TimeSeries(key, output_format='pandas')
ti = TechIndicators(key)
# Get the data, returns a tuple
# aapl_data is a pandas dataframe, aapl_meta_data is a dict
aapl_data, aapl_meta_data = ts.get_daily(symbol='AAPL')
# aapl_sma is a dict, aapl_meta_sma also a dict
aapl_sma, aapl_meta_sma = ti.get_sma(symbol='AAPL')
# Visualization
figure(num=None, figsize=(15, 6), dpi=80, facecolor='w', edgecolor='k')
aapl_data['4. close'].plot()
plt.tight_layout()
plt.grid()
plt.show()
I want it to hide the graph after a few seconds. Is this possible?
You can auto-close the PyPlot figure by adjusting the last line here and adding two more lines. Block, which is set to True by default, stops the python script from continuing to run until the figure is manually closed. By setting block to false, your code will continue to run and you can complete other tasks such as closing the figure or replacing it with a different plot.
plt.show(block=False)
plt.pause(4)
plt.close()
This will close the figure after 4 seconds.

Timeserie datetick problems when using pandas.DataFrame.plot method

I just discovered something really strange when using plot method of pandas.DataFrame. I am using pandas 0.19.1. Here is my MWE:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import pandas as pd
t = pd.date_range('1990-01-01', '1990-01-08', freq='1H')
x = pd.DataFrame(np.random.rand(len(t)), index=t)
fig, axe = plt.subplots()
x.plot(ax=axe)
plt.show(axe)
xt = axe.get_xticks()
When I try to format my xticklabels I get strange beahviours, then I insepcted objects to understand and I have found the following:
t[-1] - t[0] = Timedelta('7 days 00:00:00'), confirming the DateTimeIndex is what I expect;
xt = [175320, 175488], xticks are integers but they are not equals to a number of days since epoch (I do not have any idea about what it is);
xt[-1] - xt[0] = 168 there are more like index, there is the same amount that len(x) = 169.
This explains why I cannot succed to format my axe using:
axe.xaxis.set_major_locator(mdates.HourLocator(byhour=(0,6,12,18)))
axe.xaxis.set_major_formatter(mdates.DateFormatter("%a %H:%M"))
The first raise an error that there is to many ticks to generate
The second show that my first tick is Fri 00:00 but it should be Mon 00:00 (in fact matplotlib assumes the first tick to be 0481-01-03 00:00, oops this is where my bug is).
It looks like there is some incompatibility between pandas and matplotlib integer to date conversion but I cannot find out how to fix this issue.
If I run instead:
fig, axe = plt.subplots()
axe.plot(x)
axe.xaxis.set_major_formatter(mdates.DateFormatter("%a %H:%M"))
plt.show(axe)
xt = axe.get_xticks()
Everything works as expected but I miss all cool features from pandas.DataFrame.plot method such as curve labeling, etc. And here xt = [726468. 726475.].
How can I properly format my ticks using pandas.DataFrame.plot method instead of axe.plot and avoiding this issue?
Update
The problem seems to be about origin and scale (units) of underlying numbers for date representation. Anyway I cannot control it, even by forcing it to the correct type:
t = pd.date_range('1990-01-01', '1990-01-08', freq='1H', origin='unix', units='D')
There is a discrepancy between matplotlib and pandas representation. And I could not find any documentation of this problem.
Is this what you are going for? Note I shortened the date_range to make it easier to see the labels.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as dates
t = pd.date_range('1990-01-01', '1990-01-04', freq='1H')
x = pd.DataFrame(np.random.rand(len(t)), index=t)
# resample the df to get the index at 6-hour intervals
l = x.resample('6H').first().index
# set the ticks when you plot. this appears to position them, but not set the label
ax = x.plot(xticks=l)
# set the display value of the tick labels
ax.set_xticklabels(l.strftime("%a %H:%M"))
# hide the labels from the initial pandas plot
ax.set_xticklabels([], minor=True)
# make pretty
ax.get_figure().autofmt_xdate()
plt.show()

Plot shows automatically

I have a strange problem when plotting with matplotlib
Here is a sample code
from matplotlib.pyplot import *
for i in range(100):
plot(range(10))
xlabel("x")
This code will pop-up 100 times a figure. It seems that show() is called automatocally.
How can I make sure that after the plots no plot-windows are showed?
You can force it to use only one figure like:
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
for i in range(100):
ax.plot(range(10))
ax.set_xlabel("x")

Resources