Pyplot from pytrends not plotting correctly - python

I am currently trying to plot a simple search trend using pytrends and pyplot. This code does display a graph and the correct line; however, it also presents a second line and I am unsure where it comes from. The picture can be seen here with the correct line in blue and the additional line in orange at the bottom. My code is as follows:
from pytrends.request import TrendReq
from matplotlib import pyplot as plt
pytrends = TrendReq(hl='en')
trend = pytrends.build_payload(['tesla'])
interest = pytrends.interest_over_time()
plt.plot(interest)
plt.grid()
plt.title('Trend')
plt.ylabel('Value')
plt.xlabel('Date')
plt.show()

The graph displays this extra line because of the isPartial column, which displays a boolean value depending on whether or not the data for a given month is complete. Adding the line del interest['isPartial'] will simply resolve the issue and present this graph without the line representing the isPartial values. Altogether, the code will look like the following:
from matplotlib import pyplot as plt
pytrends = TrendReq(hl='en')
trend = pytrends.build_payload(['tesla'])
interest = pytrends.interest_over_time()
del interest['isPartial']
plt.plot(interest)
plt.grid()
plt.title('Trend')
plt.ylabel('Value')
plt.xlabel('Date')
plt.show()

Related

Combining a bar plot and a line plot in matplotlib without shifting the bar plot

I am looking for a way to combine a bar and a line plot, without the bar plot shifting when the line plot is added.
The following code is used to generate the barplot
import matplotlib.pyplot as plt
import pandas as pd
data = pd.DataFrame([[4,30,0,3,2,2,], [5,24,0,3,1,1,], [6,34,0,4,2,1], [7,18,0,2,1,1], [8,34,0,3,3,2]], columns=['t', 'Cost', 0,1,2,3])
data[[1,2,3]].plot(kind='bar')
Thus, the data looks as follows
and the following plot is generated:
Next, I add the cost information using
data['Cost'].plot(style='o--', c='black', secondary_y=True)
Running it all together returns the following graph:
The issue is that the outer bars are no longer visible. I tried changing the range on the x-axis with xlim, but that did not help, it only made it worse. There is probably an easy fix for it, which I have not been able to find anywhere online.
I don't have the issue, running your code:
That said, an easy fix is to run ax.set_xlim(-0.5, 4.5)

Line plot for multiple columns

My dataframe looks like the image below
It wanted to plot a line plot for each month. i tried plotting the line graph following some tutorial
import matplotlib.pyplot as plt
df.plot.line()
plt.show()
but i got the graph like this
isn't it supposed to have a line for each month. I cannot understand what is wrong with this.

How To Remove Extra Horizontal Line In Matplotlib Plot

I am plotting data from a .txt file using Matplotlib and although the plot looks as expected there is an odd horizontal line through the plot. This occurs across three different .txt data files I've tried. I plotted the data in Mathematica to ensure that it is not an artifact of the data. I am trying to remove the line from my data.
I've tried the accessing some of the Matplotlib methods like lines.remove() with no luck. Below is the code I'm executing and the resulting plot.
import numpy as np
import matplotlib.pyplot as plt
neon = np.loadtxt("data/neon.txt")
neon_plot = plt.plot(neon)
plt.grid()
This is an example of the horizontal line going through my plots

Cartopy Image from Grib2 file does not align with Coastlines and Borders in same CRS

This seems like it's going to be something simple that will fix my code but I think I've just looked at the code too much at the moment and need to get some fresh eyes on it. I'm simply trying to bring in a Grib2 file that I've downloaded from NCEP for the HRRR model. According to their information the grid type is Lambert Conformal with the extents of (21.13812, 21.14055, 47.84219, 47.83862) for the latitudes of the corners and (-122.7195, -72.28972, -60.91719, -134.0955) for the longitudes of the corners for the models domain.
Before even trying to zoom into my area of interest I just wanted to simply display an image in the appropriate CRS however when I try to do this for the domain of the model I get the borders and coastlines to fall within that extent but the actual image produced from the Grib2 file is just zoomed into. I've tried to use extent=[my domain extent] but it always seems to crash the notebook I'm testing it in. Here is my code and the associated image that I get from it.
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy
from mpl_toolkits.basemap import Basemap
from osgeo import gdal
gdal.SetConfigOption('GRIB_NORMALIZE_UNITS', 'NO')
plt.figure()
filename='C:\\Users\\Public\\Documents\\GRIB\\hrrr.t18z.wrfsfcf00.grib2'
grib = gdal.Open(filename, gdal.GA_ReadOnly)
z00 = grib.GetRasterBand(47)
meta00 = z00.GetMetadata()
band_description = z00.GetDescription()
bz00 = z00.ReadAsArray()
latitude_south = 21.13812 #38.5
latitude_north = 47.84219 #50
longitude_west = -134.0955 #-91
longitude_east = -60.91719 #-69
fig = plt.figure(figsize=(20, 20))
title= meta00['GRIB_COMMENT']+' at '+meta00['GRIB_SHORT_NAME']
fig.set_facecolor('white')
ax = plt.axes(projection=ccrs.LambertConformal())
ax.add_feature(cartopy.feature.BORDERS, linestyle=':')
ax.coastlines(resolution='110m')
ax.imshow(bz00,origin='upper',transform=ccrs.LambertConformal())
plt.title(title)
plt.show()
Returns Just Grib File
If I change:
ax = plt.axes(projection=ccrs.LambertConformal()
to
ax = plt.axes(projection=ccrs.LambertConformal(central_longitude=-95.5,
central_latitude=38.5,cutoff=21.13)
I get my borders but my actual data is not aligned and it creates what I'm dubbing a Batman plot.
Batman Plot
A similar issue occurs even when I do zoom into the domain and still have my borders present. The underlying data from the Grib file doesn't change to correspond to what I'm trying to get.
So as I've already said this is probably something that is an easy fix that I'm just missing but if not, it would be nice to know what step or what process I'm screwing up that I can learn from so that I don't do it in the future!
Updated 1:
I've added and changed some code and am back to getting only the image to show without the borders and coastlines showing up.
test_extent = [longitude_west,longitude_east,latitude_south,latitude_north]
ax.imshow(bz00,origin='upper',extent=test_extent)
This gives me the following image.
Looks exactly like image 1.
The other thing that I'm noticing which maybe the root cause of all of this is that when I'm printing out the value for plt.gca().get_ylim() and plt.gca().get_xlim() I'm getting hugely different values depending on what is being displayed.
It seems that my problem arises from the fact that the Grib file regardless of whether or not it can be displayed properly in other programs just doesn't play nicely with Matplotlib and Cartopy out of the box. Or at the very least does not with the Grib files that I was using. Which for sake of this perhaps helping others in the future are from the NCEP HRRR model that you can get here or here.
Everything seems to work nicely if you convert the file from Grib2 format to NetCDF format and I was able to get what I wanted with the borders, coastlines, etc. on the map. I've attached the code and the output below to show how it worked. Also I hand picked a single dataset that I wanted to display to test versus my previous code so incase you want to look at the rest of datasets available in the file you'll need to utilize ncdump or something similar to view the information on the datasets.
import numpy as np
from netCDF4 import Dataset
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy
import cartopy.feature as cfeature
from osgeo import gdal
gdal.SetConfigOption('GRIB_NORMALIZE_UNITS', 'NO')
nc_f = 'C:\\Users\\Public\\Documents\\GRIB\\test.nc' # Your filename
nc_fid = Dataset(nc_f, 'r') # Dataset is the class behavior to open the
# file and create an instance of the ncCDF4
# class
# Extract data from NetCDF file
lats = nc_fid.variables['gridlat_0'][:]
lons = nc_fid.variables['gridlon_0'][:]
temp = nc_fid.variables['TMP_P0_L1_GLC0'][:]
fig = plt.figure(figsize=(20, 20))
states_provinces = cfeature.NaturalEarthFeature(category='cultural', \
name='admin_1_states_provinces_lines',scale='50m', facecolor='none')
proj = ccrs.LambertConformal()
ax = plt.axes(projection=proj)
plt.pcolormesh(lons, lats, temp, transform=ccrs.PlateCarree(),
cmap='RdYlBu_r', zorder=1)
ax.add_feature(cartopy.feature.BORDERS, linestyle=':', zorder=2)
ax.add_feature(states_provinces, edgecolor='black')
ax.coastlines()
plt.show()
Final Preview of Map

How to save Matplotlib.pyplot.loglog to file?

I am trying to generate the log-log plot of a vector, and save the generated plot to file.
This is what I have tried so far:
import matplotlib.pyplot as plt
...
plt.loglog(deg_distribution,'b-',marker='o')
plt.savefig('LogLog.png')
I am using Jupyter Notebook, in which I get the generated graph as output after statement 2 in the above code, but the saved file is blank.
Notice that pyplot has the concept of the current figure and the current axes. All plotting commands apply to the current axes. So, make sure you plot in the right axes. Here is a WME.
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.loglog(range(100), 'b-',marker='o')
plt.savefig('test.png') # apply to the axes `ax`

Categories

Resources