python - 在 Python 上使用 plotly 方法:离线散点法在同一个图中同时比较两个因素
问题描述
我正在使用Plotly 离线 Python。我有一个csv.dateset,其中包括大学排名,它包括许多大学的引用和教学排名。我想在一个图中比较这两个因素,我离线使用 plotly但我遇到了一些我无法处理的问题,任何人都可以在这个问题上帮助我吗?
我的代码是这样的:
timesData = pd.read_csv('D:/Python/world_university_rankin/timesData.csv' ,encoding='utf-8')
edf=timesData.iloc[:100,:]
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, ip`lot
import plotly.graph_objs as go
from plotly.plotly import iplot
plotly.offline.init_notebook_mode(connected=True)
# Creating trace1
#plotly.offline.iplot({
# "data": [go.Scatter(x=[1, 2, 3, 4], y=[4, 3, 2, 1])],
# "layout": go.Layout(title="hello world")})
trace1 =plotly.offline.iplot([go.Scatter(
x = df.world_rank,
y = df.citations,
mode = "lines",
name = "citations",
marker = dict(color = 'rgba(16, 112, 2, 0.8)'),
text= df.university_name)])
# Creating trace2
trace2 = plotly.offline.iplot([go.Scatter(
x = df.world_rank,
y = df.teaching,
mode = "lines+markers",
name = "teaching",
marker = dict(color = 'rgba(80, 26, 80, 0.8)'),
text= df.university_name)])
data = [trace1, trace2]
layout = plotly.offline.iplot( [go.Layout( dict(title = 'Citation and Teaching vs World Rank of Top 100 Universities',
xaxis= dict(title= 'World Rank',ticklen= 5,zeroline= False)))])
fig = plotly.offline.iplot( [dict(data = data, layout = layout)])
py.iplot(fig)
然后面临的问题是
ValueError Traceback (most recent call last)
<ipython-input-71-f5bacdda2f25> in <module>()
28 data = [trace1, trace2]
29 layout = plotly.offline.iplot( [go.Layout( dict(title = 'Citation and Teaching vs World Rank of Top 100 Universities',
---> 30 xaxis= dict(title= 'World Rank',ticklen= 5,zeroline= False)))])
31
32
C:\ProgramData\Anaconda3\lib\site-packages\plotly\offline\offline.py in iplot(figure_or_data, show_link, link_text, validate, image, filename, image_width, image_height, config)
440 jconfig = _get_jconfig(config)
441
--> 442 figure = tools.return_figure_from_figure_or_data(figure_or_data, validate)
443
444 # Though it can add quite a bit to the display-bundle size, we include
C:\ProgramData\Anaconda3\lib\site-packages\plotly\tools.py in return_figure_from_figure_or_data(figure_or_data, validate_figure)
1506
1507 try:
-> 1508 figure = Figure(**figure).to_dict()
1509 except exceptions.PlotlyError as err:
1510 raise exceptions.PlotlyError("Invalid 'figure_or_data' argument. "
C:\ProgramData\Anaconda3\lib\site-packages\plotly\graph_objs\_figure.py in __init__(self, data, layout, frames, skip_invalid)
409 is invalid AND skip_invalid is False
410 """
--> 411 super(Figure, self).__init__(data, layout, frames, skip_invalid)
412
413 def add_area(
C:\ProgramData\Anaconda3\lib\site-packages\plotly\basedatatypes.py in __init__(self, data, layout_plotly, frames, skip_invalid)
139 # ### Import traces ###
140 data = self._data_validator.validate_coerce(data,
--> 141 skip_invalid=skip_invalid)
142
143 # ### Save tuple of trace objects ###
C:\ProgramData\Anaconda3\lib\site-packages\_plotly_utils\basevalidators.py in validate_coerce(self, v, skip_invalid)
2292
2293 if invalid_els:
-> 2294 self.raise_invalid_elements(invalid_els)
2295
2296 v = to_scalar_or_list(res)
C:\ProgramData\Anaconda3\lib\site-packages\_plotly_utils\basevalidators.py in raise_invalid_elements(self, invalid_els)
264 pname=self.parent_name,
265 invalid=invalid_els[:10],
--> 266 valid_clr_desc=self.description()))
267
268 def validate_coerce(self, v):
ValueError:
Invalid element(s) received for the 'data' property of
Invalid elements include: [Layout({
'title': 'Citation and Teaching vs World Rank of Top 100 Universities',
'xaxis': {'ticklen': 5, 'title': 'World Rank', 'zeroline': False}
})]
The 'data' property is a tuple of trace instances
that may be specified as:
- A list or tuple of trace instances
(e.g. [Scatter(...), Bar(...)])
- A list or tuple of dicts of string/value properties where:
- The 'type' property specifies the trace type
One of: ['area', 'bar', 'barpolar', 'box',
'candlestick', 'carpet', 'choropleth', 'cone',
'contour', 'contourcarpet', 'heatmap',
'heatmapgl', 'histogram', 'histogram2d',
'histogram2dcontour', 'mesh3d', 'ohlc',
'parcats', 'parcoords', 'pie', 'pointcloud',
'sankey', 'scatter', 'scatter3d',
'scattercarpet', 'scattergeo', 'scattergl',
'scattermapbox', 'scatterpolar',
'scatterpolargl', 'scatterternary', 'splom',
'streamtube', 'surface', 'table', 'violin']
- All remaining properties are passed to the constructor of
the specified trace type
(e.g. [{'type': 'scatter', ...}, {'type': 'bar, ...}])
数据链接在这里:https ://www.kaggle.com/kanncaa1/plotly-tutorial-for-beginners/data
解决方案
您的回溯告诉您该data
变量正在输入无效元素,因此请尝试skip_invalid = True
在使用时添加参数go.Layout
:
换个就行
layout = plotly.offline.iplot( [go.Layout( dict(title = 'Citation and Teaching vs World Rank of Top 100 Universities',
xaxis= dict(title= 'World Rank',ticklen= 5,zeroline= False)))])
和
layout = plotly.offline.iplot( [go.Layout( dict(title = 'Citation and Teaching vsWorld Rank of Top 100 Universities', xaxis= dict(title= 'World Rank',ticklen= 5,zeroline= False) ), skip_invalid = True)])
推荐阅读
- python - 如何找到 QComboBox 的下拉箭头被点击?
- reactjs - 如何在raectjs中将fetch转换为axios?
- c# - C#线程执行时间改变
- laravel - 未定义索引:stripetoken。我是Stripe的初学者,我无法在laravel中连接stripe
- angular-material - 如何设置用于 AngularDart Material 组件的语言?
- c++ - 我应该如何使用指针将二维数组传递给 c++ 中的函数
- swift - 如何复制 UIKit/SwiftUI 元素背景(如 UITabBar/TabView 背景)
- python - 带有日志记录的 Python Windows 计划
- python - 如何使用 BeautifulSoup 和 headers 避免 403 问题?
- python - 排序功能不会对用户输入的列表进行排序