I am trying to add tool tip to the graph, so whenever we hover around the graph it will give the info. How do i add one and make it an interactive one?
import matplotlib.pyplot as plt
import pandas as pd
import pandas as pd
from numpy import nan
from matplotlib import dates as mpl_dates
df = dataset
df["Date"] = pd.to_datetime(df["Date"]).dt.strftime('%m/%d/%Y')
#df["Date"] = pd.to_datetime(df["Date"]).apply(lambda x: x.strftime('%B-%Y'))
df.loc[df['Actuals'] == 0, ['Actuals']] = nan
df.loc[df['Actuals'] > 0, ['Predicted_Lower']] = nan
df.loc[df['Actuals'] > 0, ['Predicted_Upper']] = nan
# gca stands for 'get current axis'
ax = plt.gca()
y1 = df['Predicted_Lower']
y2 = df['Predicted_Upper']
x = df['Date']
ax.fill_between(x,y1, y2, facecolor="blue", alpha=0.7)
df.plot(kind='line',x='Date',y='Predicted', color='black', ax=ax)
df.plot(kind='line',x='Date',y='Actuals', color='green', ax=ax)
df.plot(kind='line',x='Date',y='Predicted_Lower',color='white',ax=ax)
df.plot(kind='line',x='Date',y='Predicted_Upper',color='white', ax=ax)
date_format = mpl_dates.DateFormatter('%Y-%m-%d')
plt.gca().xaxis.set_major_formatter(date_format)
locs, labels = plt.xticks()
plt.xticks(locs[::3], labels[::3], rotation=45)
plt.show()
plt.xticks(rotation=45)
plt.legend(['Predicted','Actuals'])
plt.xlabel('Date')
df.head(30)
plt.show()
using pandas, matplotlib, I am getting the data from sql server that is connected to Power BI and writing pyscripts to display graphs.
It's possible using matplotlib as discussed here.
However, you might want to look into other plotting packages such as plotly where it is builtin, default behavior.
import plotly.express as px
df = pd.DataFrame(np.arange(20), columns=['x'])
df['y'] = df['x']**2
px.line(df, x='x', y='y')
In your example, you could try something like
px.line(df, x='Date', y=Predicted, ...)
Related
I have a code in python 3.11 for a contour plot generating from an excel table using matplotlib. The result shows only first days of months on the x axis (for example 1.6.2022, 1.7.2022 ...). I want all days from the excel source table. Her's the code:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import Normalize
import pandas as pd
import matplotlib.dates as mdates
# import data from excel file
df = pd.read_excel('temperature_data.xlsx', index_col=0)
# Assign columns to variables
time = df.columns
depth = df.index
temperature = df.to_numpy()
# Creating the graph
fig, ax = plt.subplots()
min_temp = temperature.min()
max_temp = temperature.max()
cs = plt.contourf(time, depth, temperature, levels=np.arange(round(min_temp), round(max_temp)+2, 2), cmap='coolwarm', vmin=min_temp, vmax=max_temp)
cs2 = plt.contour(time, depth, temperature, levels=np.arange(round(min_temp), round(max_temp)+2, 2), colors='black')
plt.gca().invert_yaxis()
plt.clabel(cs2, inline=1, fontsize=10, fmt='%d')
plt.title('Teplota vody [°C]')
plt.xticks(rotation=90, ha='right')
ax.xaxis.set_major_formatter(mdates.DateFormatter('%d.%m.%Y'))
#ax.set_xlim(df.index.min(), df.index.max())
#ax.set_xlabel('Time')
ax.set_ylabel('hloubka [m]')
norm = Normalize(vmin=min_temp, vmax=max_temp)
plt.colorbar(cs, cmap='coolwarm', norm=norm)
plt.show()
Thank you for your help.
I want to divide and color points,val_lab(611,3) by their labels,pred_LAB(611,)
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = plt.axes(projection = '3d')
ax.set_xlabel('L')
ax.set_ylabel('A')
ax.set_zlabel('B')
for i in range(0, len(val_lab)):
ax.scatter3D(
val_lab[i,0],
val_lab[i,1],
val_lab[i,2],
s = 8,
marker='o',
c = pred_LAB
#cmap = 'rainbow'
)
#ax.legend(*points.legend_elements(), title = 'clusters')
plt.show()
The problem is it shows error,
c' argument has 611 elements, which is not acceptable for use with 'x'
with size 1, 'y' with size 1.
However, if the dataset only have ten points,it can show the figure correctly, I don't know how to solve this problem, besides, how to add legend of this figure?
In your solution you would want to replace c = pred_LAB with c = pred_LAB[i]. But you do not have to use a for loop to plot the data. You can just use the following:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# generate random input data
val_lab = np.random.randint(0,10,(611,3))
pred_LAB = np.random.uniform(0,1, (611,))
# plot data
fig = plt.figure()
ax = plt.axes(projection = '3d')
ax.set_xlabel('L')
ax.set_ylabel('A')
ax.set_zlabel('B')
# create one 3D scatter plot - no for loop
ax.scatter3D(
val_lab[:,0],
val_lab[:,1],
val_lab[:,2],
s = 8,
marker='o',
c = pred_LAB,
cmap = 'rainbow',
label='my points'
)
# add legend
plt.legend()
plt.show()
import pandas as pd
import seaborn as sns
from matplotlib import pyplot as plt
import matplotlib.pyplot as plt
sns.set(style="darkgrid")
df = pd.read_csv('Leap_Static_trials.csv')
Length = sns.swarmplot(x='name', y= 'length', data= df, color = 'green')
Width = sns.swarmplot(x='name', y= 'width', data= df, color = 'red')
plt.legend(labels=['Length','Width'])
plt.show()
From my dataset df I am plotting the length and width of the fingers taken from Leap Motion Controller. I am unable to change the legend to include the second color (red) which signifies the width.
Please find the attached figure as well. Your help is much appreciated. :)
Adding the parameter label= to a plot command usually creates the legend handles and labels automatically. In this case, seaborn creates handles for each column (so 5 of each). A trick is to create the legend with only the first and the last of the handles and the labels.
import pandas as pd
import seaborn as sns
from matplotlib import pyplot as plt
import matplotlib.pyplot as plt
sns.set(style="darkgrid")
N = 100
# df = pd.read_csv('Leap_Static_trials.csv')
names = list('abcde')
ax = plt.gca()
df = pd.DataFrame({'name': np.random.choice(names, N),
'length': np.random.normal(50, 0.7, N),
'width': np.random.normal(20, 0.5, N)})
Length = sns.swarmplot(x='name', y='length', data=df, color='green', label='Length', order=names, ax=ax)
Width = sns.swarmplot(x='name', y='width', data=df, color='red', label='Width', ax=ax)
handles, labels = ax.get_legend_handles_labels()
plt.legend([handles[0], handles[-1]], [labels[0], labels[-1]])
plt.show()
I want to fill the gridded map with colors based on the value of interest. A sample data is here:
import pandas as pd
df = pd.DataFrame()
df['lon'] = [100,105,110,115,120,125,130]
df['lat'] = [38,40,42,44,46,48,50]
df['value'] = [1,2,3,4,5,6,7]
Specifically, is it possible to do this with Cartopy? I found a similar question here:https://stackoverflow.com/questions/53412785/plotting-pandas-csv-data-onto-cartopy-map. But that post was to plot scattered points, I need to fill the grids with colors.
I myself tried:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
lon, lat = np.meshgrid(df['lon'], df['lat'])
fig = plt.figure(figsize=[15,15])
ax = plt.axes(projection=ccrs.PlateCarree())
ax.pcolormesh(lon,lat,df['variable'],latlon=True,cmap='jet')
plt.show()
The error is at ax.pcolormesh(...), it says "not enough values to unpack (expected 2, got 1)"
Many thanks for your help.
For discrete data you can create rectangular patches for each point. Here is a possible solution for your sample data set. Each row of data (lat, long, value) is used to create a rectangular patch. The value is normalized by dividing with max(value) to enable using colormap for coloring the patches.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import matplotlib.patches as mpatches
def make_rect(clon, clat, dlon, dlat):
lon_min = clon - dlon/2.
lat_min = clat - dlat/2.
lon_max = clon + dlon/2.
lat_max = clat + dlat/2.
# clockwise from LL
#lons = [lon_min, lon_min, lon_max, lon_max, lon_min]
#lats = [lat_min, lat_max, lat_max, lat_min, lat_min]
ll = [lon_min,lat_min]
ul = [lon_min,lat_max]
ur = [lon_max,lat_max]
lr = [lon_max,lat_min]
return [ll, ul, ur, lr, ll]
df = pd.DataFrame()
df['lon'] = [100,105,110,115,120,125,130]
df['lat'] = [38,40,42,44,46,48,50]
df['value'] = [1,2,3,4,5,6,7] # not suffice for meshgrid plot
# The colormap to use.
cm = plt.cm.get_cmap('jet')
fig = plt.figure(figsize=[8,6])
ax = plt.axes(projection=ccrs.PlateCarree(), extent=[95, 134, 35, 52])
# plot the red dots using the available data
# comment out if not needed
ax.plot(df['lon'], df['lat'], 'ro')
# plot rectangular patches at the data points
dlon, dlat = 5, 2 #spacings between data points
for lon1, lat1, val1 in zip(df['lon'], df['lat'], df['value']):
pcorners = make_rect(lon1, lat1, dlon, dlat)
poly = mpatches.Polygon(pcorners, ec='gray', fill=True, lw=0.25, \
fc=cm(val1 / max(df['value'])), transform=ccrs.PlateCarree())
ax.add_patch(poly)
ax.gridlines(draw_labels=True)
plt.show()
The output plot:
I am trying to generate a figure to visualize the entire covariance matrix.
However, I am not able to include the entire list of labels. See the working example below:
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import cm as cm
numberYears=len(range(2002,2018+1))
covMatrix=np.ones([numberYears,numberYears])
for count1,year1 in enumerate(range(2002,2018+1)) :
for count2,year2 in enumerate(range(2002,2018+1)) :
covMatrix[count1,count2]=1-(abs(count1-count2)/numberYears)
fig = plt.figure()
ax1 = fig.add_subplot(111)
cmap = cm.get_cmap('rainbow', 30)
cax = ax1.imshow(covMatrix, interpolation="nearest", cmap=cmap)
labels=[]
for year in range(2002,2018+1):
labels.append(str(year))
ax1.set_xticklabels(labels,fontsize=10,rotation=90)
ax1.set_yticklabels(labels,fontsize=10)
fig.colorbar(cax, ticks=[.1,.2,.3,.4,.5,.6,.7,.8,.9,1.0])
fig.savefig('map.png')
Note that my labels are [2002,2003,...,2017,2018] and the entire list is not included as a label of the figure. How can I deal with this?
Considering #ImportanceOfBeingErnest comment, I was able to find the solution. I include the argument "extent" in the function "imshow" and I also "set.xticks":
from matplotlib import pyplot as plt
from matplotlib import cm as cm
numberYears=len(range(2002,2018+1))
covMatrix=np.ones([numberYears,numberYears])
for count1,year1 in enumerate(range(2002,2018+1)) :
for count2,year2 in enumerate(range(2002,2018+1)) :
covMatrix[count1,count2]=1-(abs(count1-count2)/numberYears)
fig = plt.figure()
ax1 = fig.add_subplot(111)
cmap = cm.get_cmap('rainbow', 30)
cax = ax1.imshow(covMatrix, interpolation="nearest", cmap=cmap,extent=[2002,2018,2002,2018])
labels=[]
for year in range(2002,2018+1):
labels.append(str(year))
ax1.set_xticks(listYears)
ax1.set_yticks(listYears)
ax1.set_xticklabels(labels,fontsize=10,rotation=90)
ax1.set_yticklabels(labels,fontsize=10)
fig.colorbar(cax, ticks=[.1,.2,.3,.4,.5,.6,.7,.8,.9,1.0])
fig.savefig('mapTeste.png')