Hello everyone,
I am trying to show the track of a tropical cyclone by using a scatter plot over a spatial plot containing sst. Now while plotting the track the scatter doesn't seem to plot all the plots, mostly it is seen over land its not plotting the points. I am not able to make out where I am doing wrong in my code, if anyone can help in this regard it will be much appreciated. I am posting part of my code along with the lat long values and the plot which I have generated.I am giving the lat long data as text as below:
Lat Lon grade
10.4 87 D
10.9 86.3 D
10.9 86.3 CS
11.1 86.1 CS
11.4 86 CS
11.5 86 SCS
12 86 VSCS
12.5 86.1 VSCS
13.2 86.3 ESCS
13.4 86.2 SuCS
14 86.3 SuCS
14.9 86.5 SuCS
15.6 86.7 SuCS
16.5 86.9 ESCS
17.4 87 ESCS
18.4 87.2 ESCS
19.1 87.5 ESCS
20.6 88 ESCS
21.9 88.4 VSCS
23.3 89 SCS
24.2 89.3 CS
25 89.6 DD
25.4 89.6 D
cs=map.contourf(x,y,plt_data,clevels,cmap=plt.cm.jet)#,clevels,cmap=plt.cm.jet)
map.colorbar(cs)
df = pd.read_excel('E:/bst_trc.xls',sheet_name='Sheet6')
colors = {'SuCS': 'red', 'ESCS': 'blue', 'SCS': 'green', 'D': 'black', 'VSCS': 'orange', 'DD':'cyan',
'CS': 'magenta'}
df['x'], df['y'] = map(list(df['Lon']), list(df['Lat']))
for grade in list(df['grade'].unique()):
ax.scatter(df[df['grade'] == grade]['x'],
df[df['grade'] == grade]['y'],
s = 50,
label = grade,
facecolors = colors[grade])
plt.plot(df['x'], df['y'], 'k-', lw = 1.5)
ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.05),
fancybox=True, shadow=True, ncol=7)
#plt.savefig('E:/Super_cyclone/Amphan/sst_bfr.tif', bbox_inches='tight', dpi=300)
plt.show()
grade_unique = df['grade'].unique()
grade_unique
colormap = {a:b/len(grade_unique) for b,a in enumerate(grade_unique)}
df['color'] = df['grade'].replace(colormap)
plt.plot(df['Lon'], df['Lat'], c='k')
plt.scatter(df['Lon'], df['Lat'], c=df['color'], cmap='magma')
plt.hlines(y=25,xmin=0,xmax=100, linestyles='dashed')
plt.ylim(5,30)
plt.xlim(75,95)
Plotting the data you supplied gives this.
I rescaled to get all data points onto the plot, and drew a line at your upper ylimit. So you are missing one datapoint because of scaling.
Related
I am trying to plot the following sample table:
Time Period
HR
Legal
Fin
Leadership
Market
UX
CX
01/04/2021
6.39
5.81
7.53
7.16
6.78
7.25
7.40
7.47
6.20
01/07/2021
6.95
6.25
7.46
7.16
7.05
7.51
7.70
7.83
6.69
01/10/2021
7.41
6.43
7.65
7.50
7.25
7.74
8.00
8.04
6.90
01/01/2022
7.51
6.51
7.74
7.52
8.00
7.84
8.10
8.04
7.05
01/04/2022
7.70
6.91
7.86
7.59
7.69
7.81
8.13
8.47
7.30
01/07/2022
7.80
6.60
7.50
7.50
7.80
7.50
7.70
7.90
7.15
(Please note there are 11 columns but all of them cannot be included)
This is the code I am using:
import pandas as pd
from datetime import date, timedelta
import datetime
import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')
from statsmodels.tsa.seasonal import seasonal_decompose
from statsmodels.graphics.tsaplots import plot_pacf
from statsmodels.tsa.arima_model import ARIMA
import statsmodels.api as sm
import warnings
from plotly.offline import download_plotlyjs, init_notebook_mode, plot
from plotly.graph_objs import *
init_notebook_mode()
'set filepath'
data = pd.read_csv(inputfilepath, parse_dates=["Time Period"], index_col = "Time Period")
print(data.shape)
'Convert column from object to datetime'
#data["Time Period"] = pd.to_datetime(data['Time Period'], format="%d/%m/%Y")
data
fig, axes = plt.subplots(nrows=3, ncols=4, dpi=110, figsize=(10,6))
#axes.axis("off")
for i, ax in enumerate(axes.flatten()):
macro_data = data[data.columns[i]]
ax.plot(data, color='red', linewidth=1)
# Decorations
ax.set_title(data.columns[i], fontsize = 10)
ax.xaxis.set_ticks_position('none')
ax.yaxis.set_ticks_position('none')
ax.spines["top"].set_alpha(0)
ax.tick_params(labelsize=6)
plt.tight_layout();
I end up with 11 duplicated sub plots and each subplot has 11 lines across it. I want one line for each subplot to see each plot individually to compare. And, The plot is definitely wrong since the lines are not changing their gradients between each time period. Here is what I see:
And here is what I would (ideally want)
For reference, I am using the guide found here:
https://github.com/nachi-hebbar/Multivariate-Time-Series-Forecasting/blob/main/VAR_Model%20(1).ipynb
i want to plot the data which is shown below and compere it to a function which gives me the theoretical plot. I am able to plot the data with its uncertainty, but i am struguling to plot the mathematical function function which gives me the theoretical plot.
amplitude uncertainty position
5.2 0.429343685 0
12.2 1.836833144 1
21.4 0.672431409 2
30.2 0.927812481 3
38.2 1.163321108 4
44.2 1.340998136 5
48.4 1.506088975 6
51 1.543016526 7
51.2 1.587229032 8
49.8 1.507327436 9
46.2 1.400355669 10
40.6 1.254401849 11
32.5 0.995301462 12
24.2 0.753044487 13
14 0.58 14
7 0.29 15
here is my code so far:
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
data = pd.read_excel("Verdier_6.xlsx")
verdier = data.values
frekvens = verdier [:,3]
effektresonans = verdier [:,0]
usikkerhet = verdier [:,1]
x = np.arange(0,15,0.1)
p= 28.2
r=0.8156
v= 343.8
f= 1117
y=p*np.sqrt(1+r**2+2*r*np.cos(((2*np.pi)/(v/f))*x))
plt.plot(x,y)
plt.plot(frekvens, effektresonans)
plt.errorbar(frekvens, effektresonans, usikkerhet, fmt = "o")
plt.title("")
plt.xlabel("Posisjon, X [cm]")
plt.ylabel("Amplitude, U [mV] ")
plt.grid()
plt.show()
And here is here is a image of the plot with only experimental data shown above:
and here is an image of how my experimental and theoretical plot look:
and here is an image of how the experimental and theoretical plot should look:
I'd like to make this type of plot with multiple columns separated by small whitespace, each having different category having 3-5 (5 in this example) different observations with varying values on y axis:
actually, i can plot this plot use ggplot2. for example:
head(mtcars)
# mpg cyl disp hp drat wt qsec vs am gear carb
# Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
# Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
# Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
# Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
# Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
# Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1
library(dplyr)
library(ggplot2)
mtcars %>% reshape2::melt() %>%
ggplot(aes(x = variable, y = value)) +
geom_point() + facet_grid(~ variable) +
theme(axis.text.x = element_blank())
you set a categorical variable in your dataset,then use the facet_grid(~).this function can change your plot into multiple plot by your categrical variable
Here is an approach to draw a similar plot using Python's matplotlib. The plot has a grey background and white major and minor gridlines to delimit the zones. Getting the dots in the center of each little cell is somewhat tricky: divide into n+1 spaces and shift half a cell (1/2n). A secondary x-axis can be used to set the labels. A zorder has to be set to have the dots on top of the gridlines.
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import ticker
n = 5
cols = 7
values = [np.random.uniform(1, 10, n) for c in range(cols)]
fig, ax = plt.subplots()
ax.set_facecolor('lightgrey')
ax.xaxis.set_major_locator(ticker.MultipleLocator(1))
ax.xaxis.set_minor_locator(ticker.MultipleLocator(1 / (n)))
ax.yaxis.set_major_locator(ticker.MultipleLocator(1))
ax.grid(True, which='both', axis='both', color='white')
ax.set_xticklabels([])
ax.tick_params(axis='x', which='both', length=0)
ax.grid(which='major', axis='both', lw=3)
ax.set_xlim(1, cols + 1)
for i in range(1, cols + 1):
ax.scatter(np.linspace(i, i + 1, n, endpoint=False) + 1 / (2 * n), values[i-1], c='crimson', zorder=2)
ax2 = ax.twiny()
ax2.set_xlim(0.5, cols + 0.5)
ticks = range(1, cols + 1)
ax2.set_xticks(ticks)
ax2.set_xticklabels([f'Cat_{t:02d}' for t in ticks])
bbox = dict(boxstyle="round", ec="limegreen", fc="limegreen", alpha=0.5)
plt.setp(ax2.get_xticklabels(), bbox=bbox)
ax2.tick_params(axis='x', length=0)
plt.show()
#encoding=utf-8#
import os
import numpy as np
from matplotlib.mlab import griddata
import matplotlib.pyplot as plt
file = open('datalist.txt','r')
a = file.readlines()
file.close()
data = [lines.split('\t') for lines in a]
# read the rainfall data
file = open('lonlat.txt','r')
b = file.readlines()
file.close()
lonlat = [lines.split('\t') for lines in b]
# read the lon, lat data
main_data = []
for d_a in data:
for l_b in lonlat:
if d_a[2] == l_b[0]:
main_data.append(d_a + l_b[1:])
# integrate them
numcols, numrows = len(main_data[0]), len(main_data)
Lon = [m_a[4] for m_a in main_data]
Lat = [m_a[5] for m_a in main_data]
z = [m_a[3] for m_a in main_data] # define the lon, lat and rainfall
xi = np.linspace(22, 23, 102)
yi = np.linspace(113, 115, 102)
xi, yi = np.meshgrid(xi, yi)
x, y, z = Lon, Lat, z
zi = griddata(x, y, z, xi, yi)
fig, ax = plt.subplots(figsize=(10, 5))
im = ax.contour(xi, yi, zi, colors = 'black', linewidth = 0.2)
im = ax.contourf(xi, yi, zi)
ax.scatter(Lon, Lat, c=z, s=50,
vmin=zi.min(), vmax=zi.max())
fig.colorbar(im)
plt.xticks(())
plt.yticks(())
Here's my code. By reading the rainfall data and Lon, lat data and by integrating them, I am going to draw a contour. However, when I run the code, an error occurs:
C:\Users\15432\AppData\Local\Programs\Python\Python36\lib\site-packages\matplotlib\contour.py:1514: UserWarning: Warning: converting a masked element to nan.
self.zmax = float(z.max())
C:\Users\15432\AppData\Local\Programs\Python\Python36\lib\site-packages\matplotlib\contour.py:1515: UserWarning: Warning: converting a masked element to nan.
self.zmin = float(z.min())
C:\Users\15432\AppData\Local\Programs\Python\Python36\lib\site-packages\matplotlib\contour.py:1153: RuntimeWarning: invalid value encountered in greater
return lev[(lev > zmin) & (lev < zmax)]
C:\Users\15432\AppData\Local\Programs\Python\Python36\lib\site-packages\matplotlib\contour.py:1153: RuntimeWarning: invalid value encountered in less
return lev[(lev > zmin) & (lev < zmax)]
Traceback (most recent call last):
File "D:\Python脚本\meteotest.py", line 41, in <module>
im = ax.contour(xi, yi, zi, colors = 'black', linewidth = 0.2)
File "C:\Users\15432\AppData\Local\Programs\Python\Python36\lib\site-packages\matplotlib\__init__.py", line 1898, in inner
return func(ax, *args, **kwargs)
File "C:\Users\15432\AppData\Local\Programs\Python\Python36\lib\site-packages\matplotlib\axes\_axes.py", line 5825, in contour
contours = mcontour.QuadContourSet(self, *args, **kwargs)
File "C:\Users\15432\AppData\Local\Programs\Python\Python36\lib\site-packages\matplotlib\contour.py", line 865, in __init__
self._process_levels()
File "C:\Users\15432\AppData\Local\Programs\Python\Python36\lib\site-packages\matplotlib\contour.py", line 1199, in _process_levels
self.vmin = np.amin(self.levels)
File "C:\Users\15432\AppData\Local\Programs\Python\Python36\lib\site-packages\numpy\core\fromnumeric.py", line 2372, in amin
out=out, **kwargs)
File "C:\Users\15432\AppData\Local\Programs\Python\Python36\lib\site-packages\numpy\core\_methods.py", line 29, in _amin
return umr_minimum(a, axis, None, out, keepdims)
ValueError: zero-size array to reduction operation minimum which has no identity
I am quite confused about the value error raised. What does it mean? How can I fix the problem? Can anyone help me figure that out? Thanks in advance.
sample rainfall data:
1 蛇口 蛇口码头 116.3
2 新安 新安 100.9
3 粤海 大冲 98.2
4 福保 福田 95.1
5 沙头 沙头 94.4
6 华富 笔架山 94.3
7 桂园 蔡屋围基地 91.6
8 招商 西部通道 90.9
9 招商 东角头 88.5
10 香蜜湖 安托山东 86.8
11 新安 西乡码头 86.2
12 香蜜湖 农园 86.1
13 南园 南园 84.2
14 笋岗 笋岗 83.5
15 莲花 莲花山 83.2
16 南湖 罗湖口岸 80.8
17 龙华 龙华 80.1
18 南山 南山 78.1
19 新安 宝安 76.2
20 东门 桂园 74.9
21 新安 宝安公园 74.3
22 香蜜湖 竹子林 73.7
23 南山 妈湾港 73.3
24 沙河 世界之窗 72.4
25 大浪 大浪 71.5
26 坂田 坂田 71.4
27 招商 左炮台 70.4
28 横岗 龙口水库 67.9
29 南澳 七星湾 65.1
30 民治 民治 63.3
31 清水河 清水河 62.7
32 西乡 西乡 61.6
33 梅林 梅林水库 61.5
34 横岗 六约 59.5
35 横岗 龙口 59.3
36 坪山 田头 58.9
37 西丽 西丽 57.1
38 石岩 石岩基地 56
39 西乡 黄麻布水库 54.9
40 平湖 白泥坑 54.9
41 坪山 江岭 54
42 南湾 南湾 53.8
43 福永 福永 52.6
44 横岗 横岗 49.9
45 西丽 大勘 49.8
46 光明 圳美 48.4
47 横岗 大康 48.4
48 坪山 坪山 47.2
49 坪山 沙湖 46
50 葵涌 坝光 45.7
51 光明 塘家 45.2
52 沙井 沙井 44.6
53 福永 深圳机场 42.6
54 石岩 石岩水库 42
55 坪地 坪西 41.9
56 葵涌 葵涌 40.3
57 公明 东方 40.1
58 坑梓 坑梓 39.4
59 石岩 石岩 39.3
60 光明 光明 39.2
61 观湖 观湖 37.2
62 葵涌 葵新 37.1
63 福永 和平 37
64 横岗 荷坳 36.9
65 黄贝 罗湖 36.7
66 布吉 布吉 36.2
67 沙井 海上田园 34.7
68 龙岗 龙岗 34.4
69 平湖 平湖 34.2
70 莲塘 莲塘 33.6
71 黄贝 罗芳 32.1
72 龙城 黄龙湖水库 32
73 坪地 坪地 31.9
74 南澳 南澳渔港 30.7
75 松岗 罗田水库 30.7
76 松岗 燕川 30.6
77 沙头角 沙头角 30.4
78 大鹏 大鹏 29.8
79 南澳 柚柑湾 29.5
80 松岗 松岗 29
81 盐田 明珠 28.3
82 南澳 南澳 28.2
83 东湖 深圳水库 28.1
84 观澜 牛湖 26.7
85 葵涌 土洋 24.9
86 葵涌 溪涌 24.5
87 梅沙 大梅沙 22.9
88 坪山 竹坑 21.9
89 大鹏 核电站 20.3
90 南澳 西涌 18.8
91 公明 公明 17.7
92 大鹏 龙岐 16.7
93 盐田 三洲田 13.6
94 南头 南头 10.6
95 梅沙 背仔角 9.6
96 盐田 盐田港 7.4
97 东湖 梧桐村 4.8
98 桃源 大学城 0
99 梅沙 小梅沙 0
sample lon, lat data:
站名 经度 纬度
深圳机场北 113.8016667 22.66055556
和平 113.7883333 22.69305556
求雨坛 113.8455556 22.64694444
深圳机场南 113.8038889 22.62361111
福永 113.8175 22.67416667
深圳机场 113.8011111 22.66083333
立新水库 113.8066667 22.68638889
海上田园 113.7672222 22.72333333
海上田园 113.7672222 22.72305556
长流陂水库 113.8686111 22.71888889
共和 113.7980556 22.755
沙井 113.8197222 22.72833333
石龙仔 113.9702778 22.70027778
石岩基地 113.8941667 22.65361111
石岩水库 113.8980556 22.70472222
石岩基地 113.8936111 22.65388889
石岩 113.9347222 22.68472222
燕川 113.8602778 22.80166667
罗田水库 113.8736111 22.83694444
松岗 113.8361111 22.77916667
老虎坑 113.8388889 22.83194444
细丫岛 113.8188889 22.54722222
铁仔山 113.8555556 22.59777778
黄麻布水库 113.8622222 22.66722222
后瑞 113.83 22.63083333
西乡码头 113.8438889 22.56055556
西乡 113.8372222 22.60916667
铁岗水库 113.885 22.61277778
宝安公园 113.8930556 22.58861111
宝安 113.9061111 22.56277778
新安 113.8797222 22.55277778
大鹏 114.47 22.60055556
核电站 114.5505556 22.59694444
龙岐 114.5002778 22.56944444
葵新 114.4319444 22.61888889
官湖 114.4191667 22.60583333
罗屋田水库 114.4433333 22.65083333
径心水库 114.4505556 22.62722222
溪涌 114.3561111 22.61
土洋 114.3922222 22.615
葵涌 114.415 22.63361111
坝光 114.5144444 22.64555556
柚柑湾 114.4861111 22.48277778
东涌 114.5691667 22.49638889
七娘山 114.5455556 22.52888889
桔钓沙 114.5572222 22.56
南澳渔港 114.4844444 22.53444444
天文台 114.5575 22.48333333
西涌基地 114.5583333 22.48277778
西涌 114.5263889 22.48138889
南澳 114.4786111 22.54166667
七星湾 114.5352778 22.56194444
福田 114.0491667 22.525
水围 114.0613889 22.52222222
笔架山 114.0708333 22.56861111
华强北 114.0830556 22.55027778
莲 花 山 114.0575 22.55277778
梅林水库 114.0291667 22.5725
上梅林 114.0530556 22.5775
南园 114.0955556 22.5375
红树林 114.0302778 22.51611111
红树林 114.0305556 22.51583333
沙头 114.0163889 22.53027778
农园 114.0141667 22.54888889
安托山东 114.0094444 22.56055556
竹子林基地 114.0047222 22.54138889
竹子林 114.0047222 22.54138889
八卦岭 114.09 22.56305556
公明 113.8911111 22.78166667
东方 113.8788889 22.74388889
铁坑水库 113.9041667 22.815
塘家 113.9658333 22.735
光明 113.9536111 22.7625
育新学校 113.9558333 22.74166667
圳美 113.9544444 22.79472222
细靓北 114.0908333 22.62055556
布吉 114.1122222 22.60555556
六约 114.1694444 22.63694444
大康 114.2236111 22.64638889
横岗 114.1933333 22.64638889
荷坳 114.2338889 22.68527778
龙口水库 114.1794444 22.66222222
黄阁坑 114.2116667 22.71166667
龙口 114.195 22.67944444
黄龙湖水库 114.2361111 22.76583333
龙岗 114.2422222 22.72416667
龙岗基地 114.2108333 22.69
双龙 114.2777778 22.72861111
南湾 114.1488889 22.61638889
上李朗 114.1127778 22.65972222
坪地 114.3044444 22.7775
坪西 114.2622222 22.76694444
白泥坑 114.1508333 22.65611111
平湖 114.1230556 22.69611111
坂田 114.07 22.63083333
大浪 114.0025 22.68305556
福城 113.9983333 22.72861111
观湖 114.0397222 22.70777778
牛湖 114.0822222 22.72722222
清湖 114.045 22.67083333
龙华 114.0141667 22.65888889
民治 114.0291667 22.62305556
民治水库 114.0477778 22.61138889
翠竹 114.1277778 22.56111111
梧桐村 114.1880556 22.595
深圳水库 114.1436111 22.57166667
小梧桐 114.19 22.57111111
大梧桐 114.2138889 22.585
东门 114.0613889 22.52222222
草埔 114.1116667 22.58805556
蔡屋围基地 114.1038889 22.54722222
桂园 114.1047222 22.54972222
蔡屋围基地 114.1033333 22.54777778
罗芳 114.1508333 22.55166667
罗湖 114.1266667 22.55083333
莲塘 114.1658333 22.56472222
罗湖口岸 114.1133333 22.53083333
清水河 114.1011111 22.57194444
笋岗 114.1119444 22.55916667
13-1平台 116.1566667 21.5875
11-1平台 115.7 20.83138889
30-1平台 114.9411111 20.24444444
南山 113.9202778 22.53
妈湾港 113.8686111 22.495
南头 113.9147222 22.5475
世界之窗 113.9691667 22.53916667
蛇口码头 113.9088889 22.48
孖洲岛 113.845 22.49805556
大学城 113.9727778 22.59638889
桃源 113.9722222 22.56055556
大勘 113.9680556 22.62055556
塘朗山 113.9991667 22.59388889
西丽 113.9338889 22.605
第二高中 113.9305556 22.57222222
大冲 113.9469444 22.55111111
海珠 113.9472222 22.5225
东角头 113.9308333 22.48861111
西部通道 113.9447222 22.50388889
左炮台 113.8855556 22.47
松子坑水库 114.3427778 22.73527778
坑梓 114.3663889 22.745
田头 114.3997222 22.69583333
竹坑 114.3552778 22.7125
沙湖 114.3002778 22.67888889
江岭 114.3625 22.67166667
坪山 114.3405556 22.69444444
移动气象站A #VALUE! #VALUE!
三门岛 114.6286111 22.46055556
移动气象台 #VALUE! #VALUE!
移动气象站B #VALUE! #VALUE!
前海 113.8925 22.52472222
海山 114.2325 22.55777778
东部华侨城 114.2927778 22.62527778
大梅沙 114.2975 22.60083333
背仔角 114.3372222 22.59527778
背仔角 114.3366667 22.59555556
小梅沙 114.3247222 22.60555556
沙头角 114.2238889 22.555
正坑水库 114.2122222 22.55888889
三洲田 114.2672222 22.60083333
明珠 114.2430556 22.58388889
盐田港 114.2752778 22.56666667
With a reasonable zi I get a nice contour plot:
In [366]: xi,yi = np.meshgrid(np.arange(10),np.arange(8))
In [367]: zi = xi*yi
In [368]: fig,ax = plt.subplots(figsize=(10,6))
In [369]: ax.contour(xi,yi,zi)
Out[369]: <matplotlib.contour.QuadContourSet at 0xa959aeec>
But if all values a nan I get your error message:
In [371]: wi=zi*np.nan
In [372]: ax.contour(xi,yi,wi)
/usr/local/lib/python3.5/dist-packages/matplotlib/contour.py:1514: UserWarning: Warning: converting a masked element to nan.
self.zmax = float(z.max())
...
---> 29 return umr_minimum(a, axis, None, out, keepdims)
30
31 def _sum(a, axis=None, dtype=None, out=None, keepdims=False):
ValueError: zero-size array to reduction operation minimum which has no identity
I don't know if a smaller set of nan values does it as well or not. In any case, check your zi for nan values. Even if the z values look good, the griddata interpolation could be having problems, resulting in lots or all nan.
You may have to try other interpolation methods. See the griddata docs.
The error occurs when it tries to calculate the levels. Presumably it removes nan's and then takes the min/max. If levels is given as a parameter, we still get the warnings, but no error.
In [390]: ax.contour(xi,yi,wi,levels=[0,1])
/usr/local/lib/python3.5/dist-packages/matplotlib/contour.py:1514: UserWarning: Warning: converting a masked element to nan.
self.zmax = float(z.max())
/usr/local/lib/python3.5/dist-packages/matplotlib/contour.py:1515: UserWarning: Warning: converting a masked element to nan.
self.zmin = float(z.min())
Out[390]: <matplotlib.contour.QuadContourSet at 0xa934ef0c>
Plotting my favourite example dataframe,which looks like this:
x val1 val2 val3
0 0.0 10.0 NaN NaN
1 0.5 10.5 NaN NaN
2 1.0 11.0 NaN NaN
3 1.5 11.5 NaN 11.60
4 2.0 12.0 NaN 12.08
5 2.5 12.5 12.2 12.56
6 3.0 13.0 19.8 13.04
7 3.5 13.5 13.3 13.52
8 4.0 14.0 19.8 14.00
9 4.5 14.5 14.4 14.48
10 5.0 NaN 19.8 14.96
11 5.5 15.5 15.5 15.44
12 6.0 16.0 19.8 15.92
13 6.5 16.5 16.6 16.40
14 7.0 17.0 19.8 18.00
15 7.5 17.5 17.7 NaN
16 8.0 18.0 19.8 NaN
17 8.5 18.5 18.8 NaN
18 9.0 19.0 19.8 NaN
19 9.5 19.5 19.9 NaN
20 10.0 20.0 19.8 NaN
I have two subplots, for some other reasons it is best for me to use gridspec. The plotting code is as follows (it is quite comprehensive, so I would like to avoid major changes in the code that otherwise works perfectly and just doesn't do one unimportant detail):
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import gridspec
import matplotlib as mpl
df = pd.read_csv('H:/DocumentsRedir/pokus/dataframe.csv', delimiter=',')
# setting limits for x and y
ylimit=(0,10)
yticks1=np.arange(0,11,1)
xlimit1=(10,20)
xticks1 = np.arange(10,21,1)
# general plot formatting (axes colour, background etc.)
plt.style.use('ggplot')
plt.rc('axes',edgecolor='black')
plt.rc('axes', facecolor = 'white')
plt.rc('grid', color = 'grey')
plt.rc('grid', alpha = 0.3) # alpha is percentage of transparency
colours = ['g','b','r']
title1 = 'The plot'
# GRIDSPEC INTRO - rows, cols, distance of individual plots
fig = plt.figure(figsize=(6,4))
gs=gridspec.GridSpec(1,2, hspace=0.15, wspace=0.08,width_ratios=[1,1])
## SUBPLOT of GRIDSPEC with lines
# the first plot
axes1 = plt.subplot(gs[0,0])
for count, vals in enumerate(df.columns.values[1:]):
X = np.asarray(df[vals])
h = vals
p1 = plt.plot(X,df.index,color=colours[count],linestyle='-',linewidth=1.5,label=h)
# formatting
p1 = plt.ylim(ylimit)
p1 = plt.yticks(yticks1, yticks1, rotation=0)
p1 = axes1.yaxis.set_minor_locator(mpl.ticker.MultipleLocator(0.1))
p1 = plt.setp(axes1.get_yticklabels(),fontsize=8)
p1 = plt.gca().invert_yaxis()
p1 = plt.ylabel('x [unit]', fontsize=14)
p1 = plt.xlabel("Value [unit]", fontsize=14)
p1 = plt.tick_params('both', length=5, width=1, which='minor', direction = 'in')
p1 = axes1.xaxis.set_minor_locator(mpl.ticker.MultipleLocator(0.1))
p1 = plt.xlim(xlimit1)
p1 = plt.xticks(xticks1, xticks1, rotation=0)
p1 = plt.setp(axes1.get_xticklabels(),fontsize=8)
p1 = plt.legend(loc='best',fontsize = 8, ncol=2) #
# the second plot (something random)
axes2 = plt.subplot(gs[0,1])
for count, vals in enumerate(df.columns.values[1:]):
nonans = df[vals].dropna()
result=nonans-0.5
p2 = plt.plot(result,nonans.index,color=colours[count],linestyle='-',linewidth=1.5)
p2 = plt.ylim(ylimit)
p2 = plt.yticks(yticks1, yticks1, rotation=0)
p2 = axes2.yaxis.set_minor_locator(mpl.ticker.MultipleLocator(0.1))
p2 = plt.gca().invert_yaxis()
p2 = plt.xlim(xlimit1)
p2 = plt.xticks(xticks1, xticks1, rotation=0)
p2 = axes2.xaxis.set_minor_locator(mpl.ticker.MultipleLocator(0.1))
p2 = plt.setp(axes2.get_xticklabels(),fontsize=8)
p2 = plt.xlabel("Other value [unit]", fontsize=14)
p2 = plt.tick_params('x', length=5, width=1, which='minor', direction = 'in')
p2 = plt.setp(axes2.get_yticklabels(), visible=False)
fig.suptitle(title1, size=16)
plt.show()
However, is it possible to show the y tick labels of the second subplot on the right hand side? The current code produces this:
And I would like to know if there is an easy way to get this:
No, ok, found out it is precisely what I wanted.
I want the TICKS to be on BOTH sides, just the LABELS to be on the right. The solution above removes my ticks from the left side of the subplot, which doesn't look good. However, this answer seems to get the right solution :)
To sum up:
to get the ticks on both sides and labels on the right, this is what fixes it:
axes2.yaxis.tick_right()
axes2.yaxis.set_ticks_position('both')
And if you need the same for x axis, it's axes2.xaxis.tick_top()
try something like
axes2.yaxis.tick_right()
Just look around Python Matplotlib Y-Axis ticks on Right Side of Plot.