Setting Axis ticks of an Axes3D object - numpy

I'm new to visualizing data with matplotlib. Currently I'm trying to create an Axis3D object where each axis has ticks from 0 to 11, but only the ticks from 1 to 10 are labeled with the actual numbers. My code looks like this:
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.gca(projection='3d')
x = [3]
y = [5]
z = [8]
ax.plot(x, y, z, c='r', marker = 'o')
ax.set_xlabel('Förderung der \n lokalen Ökonomie',labelpad=10)
ax.set_ylabel('Kulturelle und \n soziale Integration',labelpad=10)
ax.set_zlabel('Einfluss auf \n natürliche Umwelt',labelpad=10)
ax.set_xticks([0,1,2,3,4,5,6,7,8,9,10,11])
ax.set_yticks([0,1,2,3,4,5,6,7,8,9,10,11])
ax.set_zticks([0,1,2,3,4,5,6,7,8,9,10,11])
x_label = ["",1,2,3,4,5,6,7,8,9,10,""]
y_label= ["",1,2,3,4,5,6,7,8,9,10,""]
z_label= ["",1,2,3,4,5,6,7,8,9,10,""]
plt.title("Hotel X, Pontresina (CH)")
ax.set_xticklabels(x_label )
ax.set_yticklabels(y_label)
ax.set_zticklabels(z_label)
plt.show()
I was able to get the code running for a 2D object but for the 3D object I only get one tick and one tick label per axis. Would be really grateful if you could help me out!
Cheers!

Related

matplotlib doesn't show BOTH a y legend (column name) AND x label (index) of mouse for a pandas dataframe?

I would like to plot a pandas dataframe where the mouse position shows in the lower right corner (x=dataframe.index) AND there is a legend (dataframe.columns). However, neither Pandas's implementation of plot nor Matplotlib's implementation of plotting a dataframe seem to suport this. Here's the code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
idx = [str(x*x) for x in range(1000)]
x = [pd.Series(np.cumsum(np.random.randn(len(idx))), idx, name = 'abc'[legendname]) for legendname in range(3)]
df = pd.DataFrame(x).transpose()
df.plot()
# The mouse x position shows as null string
plt.show()
import mplcursors
def plotme(df, title=''):
fig, ax = plt.subplots();
lines = ax.plot(df);
handles, labels = ax.get_legend_handles_labels()
print((handles,labels)) # nothing there
ax.set_title(title);
mplcursors.cursor(lines); # has no effect
# the mouse x position is correct but there is no legend
plt.show()
plotme(df,'matplotlib only')

Matplotlib: strange minor ticks with log base 2 colorbar

I am plotting some contours with tricontourf. I want the colormap to be scaled in log values and tick labels and colours bounds to be in log base 2. Here's my code:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.tri as tri
import matplotlib.ticker as ticker
import matplotlib.colors as colors
section = 'T7'
data = np.loadtxt( section + '_values.dat')
x = data[:,0]
y = data[:,1]
z = data[:,2]
triang = tri.Triangulation(x,y)
fig1, ax1 = plt.subplots()
ax1.set_aspect('equal')
bounds = [2.**-1,2.**1,2**3,2**5,2**7,2**9]
norm = colors.LogNorm()
formatter = ticker.LogFormatter(2)
tcf = ax1.tricontourf(triang, z, levels = bounds, cmap='hot_r', norm = norm )
fig1.colorbar(tcf, format=formatter)
plt.show()
And here's the result:
What are thos ugly minor ticks and how do I get rid of them?
Using Matplotlib 3.3.0 an Mac OS
You could use cb.ax.minorticks_off() to turn off the minor tick and cb.ax.minorticks_on() to turn it on.
cb = fig1.colorbar(tcf, format=formatter)
cb.ax.minorticks_off()
matplotlib.pyplot.colorbar returns a Colorbar object which extends ColorbarBase.
You can find that two functions in the document of class matplotlib.colorbar.ColorbarBase.

Visualize 1-dimensional data in a sequential colormap

I have a pandas series containing numbers ranging between 0 and 100. I want to visualise it in a horizontal bar consisting of 3 main colours.
I have tried using seaborn but all I can get is a heatmap matrix. I have also tried the below code, which is producing what I need but not in the way I need it.
x = my_column.values
y = x
t = x
fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.scatter(x, y, c=t, cmap='brg')
ax2.scatter(x, y, c=t, cmap='brg')
plt.show()
What I'm looking for is something similar to the below figure, how can I achieve that using matplotlib or seaborn?
The purpose of this is not quite clear, however, the following would produce an image like the one shown in the question:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
x = np.linspace(100,0,101)
fig, ax = plt.subplots(figsize=(6,1), constrained_layout=True)
cmap = LinearSegmentedColormap.from_list("", ["limegreen", "gold", "crimson"])
ax.imshow([x], cmap=cmap, aspect="auto",
extent=[x[0]-np.diff(x)[0]/2, x[-1]+np.diff(x)[0]/2,0,1])
ax.tick_params(axis="y", left=False, labelleft=False)
plt.show()

How can one edit the "Text" object from the "Y" and "X" axis from a gridlined cartopy geopandas plot

This question arose from another Stackoverflow Issue 1:
My problem regards the edition of the X and Y axis ticklabels from a cartopy-geopandas plot. I would like to change my Text object from each of my ticklabels (X, and Y axis) according to a certain rule.
For example, I would like to change the decimal separator ('.') into comma separator (',') from my X and Y axis ticklabels.
Here is a code that can't do that:
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import geopandas as gpd
Geopandas_DF = gpd.read_file('my_file.shp')
# setting projection and Transform
Projection=ccrs.PlateCarree()
Transform = ccrs.Geodetic(globe=ccrs.Globe(ellipse='GRS80'))
Fig, Ax = plt.subplots(1,1, subplot_kw={'projection': Projection})
Geopandas_DF.plot(ax=Ax, transform=Ax.transData)
gl = Ax.gridlines(crs=Projection , draw_labels=True, linewidth=0.5,
alpha=0.4, color='k', linestyle='--')
gl.top_labels = False
gl.right_labels = False
### Creating a function to change my Ticklabels:
def Ticker_corrector(ax):
"""
Parameter:ax, axes whose axis X and Y should be applied the function
"""
## Correcting the Axis X and Y of the main Axes
Xticks = ax.get_xticklabels()
for i in Xticks:
T = i.get_text()
T = T.replace('.',',')
i = i.set_text(T)
print(T)
ax.set_xticklabels(Xticks)
## Correcting the Axis Y
Yticks = ax.get_yticklabels()
for i in Xticks:
T = i.get_text()
T = T.replace('.',',')
i = i.set_text(T)
print(T)
ax.set_yticklabels(Yticks)
return ax
Ax = Ticker_corrector(Ax)
Fig.show()
One interesting part of the code above is that it runs without problem. The Python does not indicate any error in it, and it plots the Figure without any error warning.
Nonetheless, the Ticklabels are kept unchanged. Therefore, I need help with that problem.
I thank you for your time.
Sincerely yours,
I believe I have found a solution. It may not work always, but it certainly solved my problem.
The fundamental basis for the solution was to set the "Locale" of my matplotlib before creating my plot.
Here is an example:
import locale
locale.setlocale(locale.LC_ALL, "Portuguese_Brazil.1252")
import matplotlib as mpl
mpl.rcParams['axes.formatter.use_locale'] = True
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import geopandas as gpd
Geopandas_DF = gpd.read_file('my_file.shp')
# setting projection and Transform
Projection=ccrs.PlateCarree()
Transform = ccrs.Geodetic(globe=ccrs.Globe(ellipse='GRS80'))
Fig, Ax = plt.subplots(1,1, subplot_kw={'projection': Projection})
Geopandas_DF.plot(ax=Ax, transform=Ax.transData)
gl = Ax.gridlines(crs=Projection , draw_labels=True, linewidth=0.5,
alpha=0.4, color='k', linestyle='--')
gl.top_labels = False
gl.right_labels = False
Fig.show()

Python Subplot 3d Surface and Heat Map

I plan to create a figure in matplotlib, with a 3D surface on the left and its corresponding contour map on the right.
I used subplots but it only show the contour map (with blank space for the surface), and a separate figure for the surface.
Is it possible to create these plots in one figure side-by side?
EDIT: The code is as follows:
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d
import numpy as np
x = np.arange(-5, 5, 0.25)
y = np.arange(-5, 5, 0.25)
x, y = np.meshgrid(x, y)
r = np.sqrt(x**2 + y**2)
z = np.sin(r)
fig, (surf, cmap) = plt.subplots(1, 2)
fig = plt.figure()
surf = fig.gca(projection='3d')
surf.plot_surface(x,y,z)
cmap.contourf(x,y,z,25)
plt.show()
I guess it's hard to use plt.subplots() in order to create a grid of plots with different projections.
So the most straight forward solution is to create each subplot individually with plt.subplot.
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d
import numpy as np
x = np.arange(-5, 5, 0.25)
y = np.arange(-5, 5, 0.25)
x, y = np.meshgrid(x, y)
r = np.sqrt(x**2 + y**2)
z = np.sin(r)
ax = plt.subplot(121, projection='3d')
ax.plot_surface(x,y,z)
ax2 = plt.subplot(122)
ax2.contourf(x,y,z,25)
plt.show()
Of course one may also use the gridspec capabilities for more sophisticated grid structures.