在R

时间:2018-07-22 07:44:58

标签: r ggplot2

我有一个包含宾夕法尼亚州县(67)和每个县的发生频率的数据集。现在,我想用频率创建一个热图。我正在使用R的地图库:

require(maps)
m<-map("county","Pennsylvania")

这将返回如下地图:

enter image description here

使用此dataset,我创建了每个县的点数汇总表。 dput(Frequency)的输出如下:

Frequency <- structure(list(County_join = c("adams", "allegheny", "armstrong", 
"beaver", "bedford", "berks", "blair", "bradford", "bucks", "butler", 
"cambria", "cameron", "carbon", "centre", "chester", "clarion", 
"clearfield", "clinton", "columbia", "crawford", "cumberland", 
"dauphin", "delaware", "elk", "erie", "fayette", "forest", "franklin", 
"fulton", "greene", "huntingdon", "indiana", "jefferson", "juniata", 
"lackawanna", "lancaster", "lawrence", "lebanon", "lehigh", "luzerne", 
"lycoming", "mckean", "mercer", "mifflin", "monroe", "montgomery", 
"montour", "northampton", "northumberland", "perry", "philadelphia", 
"pike", "potter", "schuylkill", "snyder", "somerset", "sullivan", 
"susquehanna", "tioga", "union", "venango", "warren", "washington", 
"wayne", "westmoreland", "wyoming", "york", NA), Frequencies = c(312L, 
5367L, 263L, 537L, 136L, 1176L, 431L, 203L, 1475L, 541L, 626L, 
31L, 322L, 398L, 984L, 174L, 327L, 146L, 245L, 373L, 500L, 954L, 
1257L, 174L, 1008L, 554L, 46L, 230L, 24L, 104L, 102L, 272L, 177L, 
38L, 1159L, 1040L, 219L, 292L, 933L, 1701L, 458L, 211L, 399L, 
126L, 592L, 1890L, 72L, 868L, 330L, 94L, 5300L, 212L, 92L, 724L, 
91L, 311L, 48L, 172L, 147L, 87L, 125L, 153L, 795L, 269L, 1388L, 
118L, 872L, 1590L)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, 
-68L))

如何将其转换为有色的频率色热图?

2 个答案:

答案 0 :(得分:3)

InvalidArgumentError                      Traceback (most recent call last)
~\Miniconda3\lib\site-packages\tensorflow\python\client\session.py in _do_call(self, fn, *args)
   1021     fetch_handler = _FetchHandler(self._graph, fetches, {})
-> 1022 
   1023     # Set up a graph with feeds and fetches for partial run.

~\Miniconda3\lib\site-packages\tensorflow\python\client\session.py in _run_fn(session, feed_dict, fetch_list, target_list, options, run_metadata)
   1003     for feed in feeds:
-> 1004       for subfeed in _feed_fn(feed):
   1005         try:

~\Miniconda3\lib\contextlib.py in __exit__(self, type, value, traceback)
     65             try:
---> 66                 next(self.gen)
     67             except StopIteration:

~\Miniconda3\lib\site-packages\tensorflow\python\framework\errors_impl.py in raise_exception_on_not_ok_status()
    468     ABORTED: AbortedError,
--> 469     OUT_OF_RANGE: OutOfRangeError,
    470     UNIMPLEMENTED: UnimplementedError,

InvalidArgumentError: NodeDef mentions attr 'data_format' not in Op<name=DepthwiseConv2dNative; signature=input:T, filter:T -> output:T; attr=T:type,allowed=[DT_FLOAT, DT_DOUBLE]; attr=strides:list(int); attr=padding:string,allowed=["SAME", "VALID"]>; NodeDef: FeatureExtractor/MobilenetV1/MobilenetV1/Conv2d_1_depthwise/depthwise = DepthwiseConv2dNative[T=DT_FLOAT, data_format="NHWC", padding="SAME", strides=[1, 1, 1, 1], _device="/job:localhost/replica:0/task:0/cpu:0"](FeatureExtractor/MobilenetV1/MobilenetV1/Conv2d_0/Relu6, FeatureExtractor/MobilenetV1/Conv2d_1_depthwise/depthwise_weights/read)
     [[Node: FeatureExtractor/MobilenetV1/MobilenetV1/Conv2d_1_depthwise/depthwise = DepthwiseConv2dNative[T=DT_FLOAT, data_format="NHWC", padding="SAME", strides=[1, 1, 1, 1], _device="/job:localhost/replica:0/task:0/cpu:0"](FeatureExtractor/MobilenetV1/MobilenetV1/Conv2d_0/Relu6, FeatureExtractor/MobilenetV1/Conv2d_1_depthwise/depthwise_weights/read)]]

During handling of the above exception, another exception occurred:

InvalidArgumentError                      Traceback (most recent call last)
<ipython-input-104-4c1ce36f9a76> in <module>()
     14       num_detections = detection_graph.get_tensor_by_name('num_detections:0')
     15       # Actual detection.
---> 16       (boxes, scores, classes, num_detections) = sess.run([boxes, scores, classes, num_detections],feed_dict={image_tensor: image_np_expanded})
     17       # Visualization of the results of a detection.
     18       vis_util.visualize_boxes_and_labels_on_image_array(

~\Miniconda3\lib\site-packages\tensorflow\python\client\session.py in run(self, fetches, feed_dict, options, run_metadata)
    765       print(c.eval())
    766 
--> 767     sess.close()
    768     ```
    769 

~\Miniconda3\lib\site-packages\tensorflow\python\client\session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
    963     Note that contrary to `run`, `feeds` only specifies the graph elements.
    964     The tensors will be supplied by the subsequent `partial_run` calls.
--> 965 
    966     Args:
    967       fetches: A single graph element, or a list of graph elements.

~\Miniconda3\lib\site-packages\tensorflow\python\client\session.py in _do_run(self, handle, target_list, fetch_list, feed_dict, options, run_metadata)
   1013             feed_list.append(compat.as_bytes(subfeed_t.name))
   1014         except Exception as e:
-> 1015           e.message = ('Cannot interpret feed_list key as Tensor: ' + e.message)
   1016           e.args = (e.message,)
   1017           raise e

~\Miniconda3\lib\site-packages\tensorflow\python\client\session.py in _do_call(self, fn, *args)
   1033 
   1034     if self._created_with_new_api:
-> 1035       # pylint: disable=protected-access
   1036       final_fetches = [t._as_tf_output() for t in fetch_handler.fetches()]
   1037       final_targets = [op._c_op for op in fetch_handler.targets()]

InvalidArgumentError: NodeDef mentions attr 'data_format' not in Op<name=DepthwiseConv2dNative; signature=input:T, filter:T -> output:T; attr=T:type,allowed=[DT_FLOAT, DT_DOUBLE]; attr=strides:list(int); attr=padding:string,allowed=["SAME", "VALID"]>; NodeDef: FeatureExtractor/MobilenetV1/MobilenetV1/Conv2d_1_depthwise/depthwise = DepthwiseConv2dNative[T=DT_FLOAT, data_format="NHWC", padding="SAME", strides=[1, 1, 1, 1], _device="/job:localhost/replica:0/task:0/cpu:0"](FeatureExtractor/MobilenetV1/MobilenetV1/Conv2d_0/Relu6, FeatureExtractor/MobilenetV1/Conv2d_1_depthwise/depthwise_weights/read)
     [[Node: FeatureExtractor/MobilenetV1/MobilenetV1/Conv2d_1_depthwise/depthwise = DepthwiseConv2dNative[T=DT_FLOAT, data_format="NHWC", padding="SAME", strides=[1, 1, 1, 1], _device="/job:localhost/replica:0/task:0/cpu:0"](FeatureExtractor/MobilenetV1/MobilenetV1/Conv2d_0/Relu6, FeatureExtractor/MobilenetV1/Conv2d_1_depthwise/depthwise_weights/read)]]

Caused by op 'FeatureExtractor/MobilenetV1/MobilenetV1/Conv2d_1_depthwise/depthwise', defined at:
  File "C:\Users\Johny Sir\Miniconda3\lib\runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "C:\Users\Johny Sir\Miniconda3\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "C:\Users\Johny Sir\Miniconda3\lib\site-packages\ipykernel_launcher.py", line 16, in <module>
    app.launch_new_instance()
  File "C:\Users\Johny Sir\Miniconda3\lib\site-packages\traitlets\config\application.py", line 658, in launch_instance
    app.start()
  File "C:\Users\Johny Sir\Miniconda3\lib\site-packages\ipykernel\kernelapp.py", line 486, in start
    self.io_loop.start()
  File "C:\Users\Johny Sir\Miniconda3\lib\site-packages\tornado\platform\asyncio.py", line 127, in start
    self.asyncio_loop.run_forever()
  File "C:\Users\Johny Sir\Miniconda3\lib\asyncio\base_events.py", line 421, in run_forever
    self._run_once()
  File "C:\Users\Johny Sir\Miniconda3\lib\asyncio\base_events.py", line 1425, in _run_once
    handle._run()
  File "C:\Users\Johny Sir\Miniconda3\lib\asyncio\events.py", line 127, in _run
    self._callback(*self._args)
  File "C:\Users\Johny Sir\Miniconda3\lib\site-packages\tornado\ioloop.py", line 759, in _run_callback
    ret = callback()
  File "C:\Users\Johny Sir\Miniconda3\lib\site-packages\tornado\stack_context.py", line 276, in null_wrapper
    return fn(*args, **kwargs)
  File "C:\Users\Johny Sir\Miniconda3\lib\site-packages\zmq\eventloop\zmqstream.py", line 536, in <lambda>
    self.io_loop.add_callback(lambda : self._handle_events(self.socket, 0))
  File "C:\Users\Johny Sir\Miniconda3\lib\site-packages\zmq\eventloop\zmqstream.py", line 450, in _handle_events
    self._handle_recv()
  File "C:\Users\Johny Sir\Miniconda3\lib\site-packages\zmq\eventloop\zmqstream.py", line 480, in _handle_recv
    self._run_callback(callback, msg)
  File "C:\Users\Johny Sir\Miniconda3\lib\site-packages\zmq\eventloop\zmqstream.py", line 432, in _run_callback
    callback(*args, **kwargs)
  File "C:\Users\Johny Sir\Miniconda3\lib\site-packages\tornado\stack_context.py", line 276, in null_wrapper
    return fn(*args, **kwargs)
  File "C:\Users\Johny Sir\Miniconda3\lib\site-packages\ipykernel\kernelbase.py", line 283, in dispatcher
    return self.dispatch_shell(stream, msg)
  File "C:\Users\Johny Sir\Miniconda3\lib\site-packages\ipykernel\kernelbase.py", line 233, in dispatch_shell
    handler(stream, idents, msg)
  File "C:\Users\Johny Sir\Miniconda3\lib\site-packages\ipykernel\kernelbase.py", line 399, in execute_request
    user_expressions, allow_stdin)
  File "C:\Users\Johny Sir\Miniconda3\lib\site-packages\ipykernel\ipkernel.py", line 208, in do_execute
    res = shell.run_cell(code, store_history=store_history, silent=silent)
  File "C:\Users\Johny Sir\Miniconda3\lib\site-packages\ipykernel\zmqshell.py", line 537, in run_cell
    return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)
  File "C:\Users\Johny Sir\Miniconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2662, in run_cell
    raw_cell, store_history, silent, shell_futures)
  File "C:\Users\Johny Sir\Miniconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2785, in _run_cell
    interactivity=interactivity, compiler=compiler, result=result)
  File "C:\Users\Johny Sir\Miniconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2903, in run_ast_nodes
    if self.run_code(code, result):
  File "C:\Users\Johny Sir\Miniconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2963, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-100-0d8b8f2357e8>", line 7, in <module>
    tf.import_graph_def(od_graph_def, name='')
  File "C:\Users\Johny Sir\Miniconda3\lib\site-packages\tensorflow\python\framework\importer.py", line 287, in import_graph_def
    if colocation_node_name != op.name:
  File "C:\Users\Johny Sir\Miniconda3\lib\site-packages\tensorflow\python\framework\ops.py", line 2395, in create_op
    for a description of the valid feed values.
  File "C:\Users\Johny Sir\Miniconda3\lib\site-packages\tensorflow\python\framework\ops.py", line 1264, in __init__
    (dtypes.as_dtype(dtype).name, value.dtype.name, str(value)))

InvalidArgumentError (see above for traceback): NodeDef mentions attr 'data_format' not in Op<name=DepthwiseConv2dNative; signature=input:T, filter:T -> output:T; attr=T:type,allowed=[DT_FLOAT, DT_DOUBLE]; attr=strides:list(int); attr=padding:string,allowed=["SAME", "VALID"]>; NodeDef: FeatureExtractor/MobilenetV1/MobilenetV1/Conv2d_1_depthwise/depthwise = DepthwiseConv2dNative[T=DT_FLOAT, data_format="NHWC", padding="SAME", strides=[1, 1, 1, 1], _device="/job:localhost/replica:0/task:0/cpu:0"](FeatureExtractor/MobilenetV1/MobilenetV1/Conv2d_0/Relu6, FeatureExtractor/MobilenetV1/Conv2d_1_depthwise/depthwise_weights/read)
     [[Node: FeatureExtractor/MobilenetV1/MobilenetV1/Conv2d_1_depthwise/depthwise = DepthwiseConv2dNative[T=DT_FLOAT, data_format="NHWC", padding="SAME", strides=[1, 1, 1, 1], _device="/job:localhost/replica:0/task:0/cpu:0"](FeatureExtractor/MobilenetV1/MobilenetV1/Conv2d_0/Relu6, FeatureExtractor/MobilenetV1/Conv2d_1_depthwise/depthwise_weights/read)]]

enter image description here

您可以检查here以获得更多信息。希望对您有所帮助。

答案 1 :(得分:1)

require(maps)
require(sf)
require(dplyr)

# load freq data
df <- read.csv("D:/GoogleDrive/stack/df.csv", sep = ",")

# select administrative divisions with 5 digits code i.e. county level
df_five = df %>% filter(grepl(".*\\b(\\d{5})\\b.*", LID)) %>% 
                mutate(NAME = gsub(" County", "", County)) %>% 
                select(-County)

# find county frequencies
freq <- df_five %>% 
  group_by( NAME) %>% 
  summarise(n = length(NAME)) %>% 
  arrange(-n) %>% 
  filter(NAME != "")

# join county info to count frequency
res <- freq %>% left_join(df_five %>% select(LID, NAME), by="NAME")

# define color buckets
colors = c("#F1EEF6", "#D4B9DA", "#C994C7", "#DF65B0", "#DD1C77", "#980043", "#4c0021")
res$colorBuckets <- as.numeric(cut(res$n, c(0, 500, 1000, 1500, 2000, 2500, 3500)))
leg.txt <- c("< 500", "500-1000", "1000-1500", "1500-2000", "2000-2500", "2500-3500")

# draw map
map("county", "Pennsylvania", col = colors, fill = TRUE, resolution = 0,
    lty = 0, projection = "polyconic")
map("state", col = "white", fill = FALSE, add = TRUE, lty = 1, lwd = 0.2,
    projection="polyconic")
legend("topright", leg.txt, horiz = TRUE, fill = colors)

enter image description here